我有一个字典,其中键是字符串,值是整数。
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])
当前回答
+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(d, key=d.get)
# which is equivalent to
max(d, key=lambda k: d.get(k))
要返回键值对,使用:
max(d.items(), key=lambda k: k[1])
max(stats, key=stats.get)
对于科学python用户,这里有一个使用Pandas的简单解决方案:
import pandas as pd
pd.Series({'a': 1000, 'b': 3000, 'c': 100}).idxmax()
>>> b
key, value = max(stats.iteritems(), key=lambda x:x[1])
如果你不关心价值(我会很惊讶,但是),你可以做:
key, _ = max(stats.iteritems(), key=lambda x:x[1])
我更喜欢元组解包,而不是表达式末尾的[0]下标。 我从来都不太喜欢lambda表达式的可读性,但我发现这个比operator.itemgetter(1)更好。
如何:
max(zip(stats.keys(), stats.values()), key=lambda t : t[1])[0]