我有一个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(1))[0]
而不是在内存使用中构建新列表stats.iteritems()
。该函数的key
参数max()
是计算用于确定如何对项目进行排名的键的函数。
请注意,如果要使用另一个键值对“ d”:3000,则此方法将仅返回两个值中的一个,即使它们都具有最大值。
>>> import operator
>>> stats = {'a':1000, 'b':3000, 'c': 100, 'd':3000}
>>> max(stats.iteritems(), key=operator.itemgetter(1))[0]
'b'
如果使用Python3:
>>> max(stats.items(), key=operator.itemgetter(1))[0]
'b'
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句