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

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

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


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

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

当前回答

Counter = 0
for word in stats.keys():
    if stats[word]> counter:
        Counter = stats [word]
print Counter

其他回答

在stats为空的情况下,可以在找到value key之前检查一个条件,

stats = {'a':1000, 'b':3000, 'c': 100}
max_key = None
if bool(stats):
   max_key = max(stats, key=stats.get)
print(max_key)

这可以首先检查字典是否为空,然后处理。

>>> b

试试这个:

sorted(dict_name, key=dict_name.__getitem__, reverse=True)[0]
max(stats, key=stats.get)

根据所选答案中的注释迭代解决方案…

在Python 3中:

max(stats.keys(), key=(lambda k: stats[k]))

在Python 2中:

max(stats.iterkeys(), key=(lambda k: stats[k]))
key, value = max(stats.iteritems(), key=lambda x:x[1])

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

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

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