我有一个字典,其中键是字符串,值是整数。

stats = {'a': 1, 'b': 3000, 'c': 0}

如何获得具有最大值的键?在这种情况下,它是'b'。


有没有比使用带有反向键值元组的中间列表更好的方法?

inverse = [(value, key) for key, value in stats.items()]
print(max(inverse)[1])

当前回答

在这种情况下,你有多个具有相同值的键,例如:

stats = {'a':1000, 'b':3000, 'c': 100, 'd':3000, 'e':3000}

你可以得到一个包含所有最大值键的集合,如下所示:

from collections import defaultdict
from collections import OrderedDict

groupedByValue = defaultdict(list)
for key, value in sorted(stats.items()):
    groupedByValue[value].append(key)

# {1000: ['a'], 3000: ['b', 'd', 'e'], 100: ['c']}

groupedByValue[max(groupedByValue)]
# ['b', 'd', 'e']

其他回答

如果有一个以上的元素,我的值是最大的。我会列出所有值为最大值的键。

>>> 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()

max(stats, key=stats.get, default=None)

如果stats可以是一个空字典,则只使用max(stats, key=stats.get)将引发ValueError。

这个答案是安全的,只要在字典中不是一个可能的键。

你可以使用:

max(d, key=d.get) 
# which is equivalent to 
max(d, key=lambda k: d.get(k))

要返回键值对,使用:

max(d.items(), key=lambda k: k[1])
Counter = 0
for word in stats.keys():
    if stats[word]> counter:
        Counter = stats [word]
print Counter

下面是两种简单的方法从给定的字典中提取键的最大值

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表达式的解决方案似乎对较小的输入执行得更好。