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

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

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


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

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

当前回答

+1到@Aric Coady最简单的解决方案。 还有一种方法是随机选择字典中最大值的键之一:

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

import random
maxV = max(stats.values())
# Choice is one of the keys with max value
choice = random.choice([key for key, value in stats.items() if value == maxV])

其他回答

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

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

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

我更喜欢元组解包,而不是表达式末尾的[0]下标。 我从来都不太喜欢lambda表达式的可读性,但我发现这个比operator.itemgetter(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']

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

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])```

+1到@Aric Coady最简单的解决方案。 还有一种方法是随机选择字典中最大值的键之一:

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

import random
maxV = max(stats.values())
# Choice is one of the keys with max value
choice = random.choice([key for key, value in stats.items() if value == maxV])