我有一个字典,其中键是字符串,值是整数。
stats = {'a': 1, 'b': 3000, 'c': 0}
如何获得具有最大值的键?在这种情况下,它是'b'。
有没有比使用带有反向键值元组的中间列表更好的方法?
inverse = [(value, key) for key, value in stats.items()]
print(max(inverse)[1])
我有一个字典,其中键是字符串,值是整数。
stats = {'a': 1, 'b': 3000, 'c': 0}
如何获得具有最大值的键?在这种情况下,它是'b'。
有没有比使用带有反向键值元组的中间列表更好的方法?
inverse = [(value, key) for key, value in stats.items()]
print(max(inverse)[1])
当前回答
我在这里寻找如何根据mydict.values()的值返回mydict.keys()。我不是只返回一个键,而是返回前x个值。
这个解决方案比使用max()函数更简单,你可以很容易地改变返回值的数量:
stats = {'a':1000, 'b':3000, 'c': 100}
x = sorted(stats, key=(lambda key:stats[key]), reverse=True)
['b', 'a', 'c']
如果你想要一个排名最高的键,只需使用索引:
x[0]
['b']
如果你想要前两个排名最高的键,只需使用列表切片:
x[:2]
['b', 'a']
其他回答
下面是两种简单的方法从给定的字典中提取键的最大值
import time
stats = {
"a" : 1000,
"b" : 3000,
"c" : 90,
"d" : 74,
"e" : 72,
}
start_time = time.time_ns()
max_key = max(stats, key = stats.get)
print("Max Key [", max_key, "]Time taken (ns)", time.time_ns() - start_time)
start_time = time.time_ns()
max_key = max(stats, key=lambda key: stats[key])
print("Max Key with Lambda[", max_key, "]Time taken (ns)", time.time_ns() - start_time)
输出
Max Key [ b ] Time taken (ns) 3100
Max Key with Lambda [ b ] Time taken (ns) 1782
使用Lambda表达式的解决方案似乎对较小的输入执行得更好。
堆队列是一个通用的解决方案,它允许你提取按值排序的前n个键:
from heapq import nlargest
stats = {'a':1000, 'b':3000, 'c': 100}
res1 = nlargest(1, stats, key=stats.__getitem__) # ['b']
res2 = nlargest(2, stats, key=stats.__getitem__) # ['b', 'a']
res1_val = next(iter(res1)) # 'b'
注意dict类型。__getitem__是由语法糖dict[]调用的方法。与dict相反。如果没有找到键,它将返回KeyError,这在这里是不可能发生的。
如果有一个以上的元素,我的值是最大的。我会列出所有值为最大值的键。
>>> stats = {'a':1000, 'b':3000, 'c': 100, 'd':3000}
>>> [key for m in [max(stats.values())] for key,val in stats.iteritems() if val == m]
['b', 'd']
这将给你'b'和任何其他最大键。
注意:对于python 3使用stats.items()而不是stats.iteritems()
对于科学python用户,这里有一个使用Pandas的简单解决方案:
import pandas as pd
pd.Series({'a': 1000, 'b': 3000, 'c': 100}).idxmax()
>>> b
例子:
stats = {'a':1000, 'b':3000, 'c': 100}
如果你想用它的键找到Max值,也许下面的步骤很简单,不需要任何相关的函数。
max(stats, key=stats.get)
输出是具有Max值的键。