我有一个字典,其中键是字符串,值是整数。
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])
当前回答
下面是两种简单的方法从给定的字典中提取键的最大值
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表达式的解决方案似乎对较小的输入执行得更好。
其他回答
如何:
max(zip(stats.keys(), stats.values()), key=lambda t : t[1])[0]
我对这些答案都不满意。Max总是选择第一个具有Max值的键。字典可以有多个具有该值的键。
def keys_with_top_values(my_dict):
return [key for (key, value) in my_dict.items() if value == max(my_dict.values())]
把这个答案贴出来,希望能帮助到别人。 请看下面的SO帖子
在平局的情况下,Python会选择哪个最大值?
你可以使用运算符。Itemgetter:
import operator
stats = {'a': 1000, 'b': 3000, 'c': 100}
max(stats.iteritems(), key=operator.itemgetter(1))[0]
并且使用stats.iteritems()而不是在内存中构建一个新的列表。max()函数的key参数是一个函数,它计算一个用于确定如何对项目排序的键。
请注意,如果你有另一个键值对'd': 3000,这个方法将只返回其中一个,即使它们都有最大值。
>>> import operator
>>> stats = {'a': 1000, 'b': 3000, 'c': 100, 'd': 3000}
>>> max(stats.iteritems(), key=operator.itemgetter(1))[0]
'b'
如果使用Python3:
>>> max(stats.items(), key=operator.itemgetter(1))[0]
'b'
max(stats, key=stats.get)
Counter = 0
for word in stats.keys():
if stats[word]> counter:
Counter = stats [word]
print Counter