我有一个字典,其中键是字符串,值是整数。
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])
当前回答
key, value = max(stats.iteritems(), key=lambda x:x[1])
如果你不关心价值(我会很惊讶,但是),你可以做:
key, _ = max(stats.iteritems(), key=lambda x:x[1])
我更喜欢元组解包,而不是表达式末尾的[0]下标。 我从来都不太喜欢lambda表达式的可读性,但我发现这个比operator.itemgetter(1)更好。
其他回答
例子:
stats = {'a':1000, 'b':3000, 'c': 100}
如果你想用它的键找到Max值,也许下面的步骤很简单,不需要任何相关的函数。
max(stats, key=stats.get)
输出是具有Max值的键。
与集合。你可以这样做
>>> 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.
对于科学python用户,这里有一个使用Pandas的简单解决方案:
import pandas as pd
pd.Series({'a': 1000, 'b': 3000, 'c': 100}).idxmax()
>>> b
max(stats, key=stats.get, default=None)
如果stats可以是一个空字典,则只使用max(stats, key=stats.get)将引发ValueError。
这个答案是安全的,只要在字典中不是一个可能的键。
+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])