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

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

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


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

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

当前回答

堆队列是一个通用的解决方案,它允许你提取按值排序的前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,这在这里是不可能发生的。

其他回答

max(stats, key=stats.get)

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

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

只是添加一个你想要选择某些键而不是所有键的情况:

stats = {'a':1000, 'b':3000, 'c': 100, 'd':3000, 'e':3000}
keys_to_search = ["a", "b", "c"]

max([k for k in keys_to_search], key=lambda x: stats[x])```
key, value = max(stats.iteritems(), key=lambda x:x[1])

如果你不关心价值(我会很惊讶,但是),你可以做:

key, _ = max(stats.iteritems(), key=lambda x:x[1])

我更喜欢元组解包,而不是表达式末尾的[0]下标。 我从来都不太喜欢lambda表达式的可读性,但我发现这个比operator.itemgetter(1)更好。

与集合。你可以这样做

>>> import collections
>>> stats = {'a':1000, 'b':3000, 'c': 100}
>>> stats = collections.Counter(stats)
>>> stats.most_common(1)
[('b', 3000)]

如果合适,可以从一个空集合开始。计数并加进去

>>> stats = collections.Counter()
>>> stats['a'] += 1
:
etc.