在字典中获得最大值的键? [英] Getting key with maximum value in dictionary?
问题描述
我有一个字典
:键是字符串,值是整数。
示例:
stats = {'a':1000,'b':3000,'c':100}
我想获得'b'
作为答案,因为它是关键具有较高的价值。
我做了以下操作,使用带有反向键值元组的中间列表:
inverse = [(value,key)for key,value in stats.items()]
print max(inverse)[1]
这是一个更好(甚至更优雅)的方法吗?
解决方案您可以使用
operator.itemgetter
:import operator
stats = {'a':1000,'b':3000,'c':100}
max(stats.iteritems(),key = operator.itemgetter ))[0]
而不是在内存中构建新的列表使用
stats.iteritems()
。key
的key参数是一个函数,用于计算用于确定如何排列的键
请注意,如果您要使用另一个键值对'd':3000,则此方法将只返回一个 两个即使它们都具有最大值。
>>>导入操作符
>>> stats = {'a':1000,'b':3000,'c':100,'d':3000}
>>> max(stats.iteritems(),key = operator.itemgetter(1))[0]
'b'
I have a
dictionary
: keys are strings, values are integers.Example:
stats = {'a':1000, 'b':3000, 'c': 100}
I'd like to get
'b'
as an answer, since it's the key with a higher value.I did the following, using an intermediate list with reversed key-value tuples:
inverse = [(value, key) for key, value in stats.items()] print max(inverse)[1]
Is that one the better (or even more elegant) approach?
解决方案You can use
operator.itemgetter
for that:import operator stats = {'a':1000, 'b':3000, 'c': 100} max(stats.iteritems(), key=operator.itemgetter(1))[0]
And instead of building a new list in memory use
stats.iteritems()
. Thekey
parameter to themax()
function is a function that computes a key that is used to determine how to rank items.Please note that if you were to have another key-value pair 'd': 3000 that this method will only return one of the two even though they both have the maximum value.
>>> import operator >>> stats = {'a':1000, 'b':3000, 'c': 100, 'd':3000} >>> max(stats.iteritems(), key=operator.itemgetter(1))[0] 'b'
这篇关于在字典中获得最大值的键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!