在字典中获取最大值的键? [英] Getting key with maximum value in dictionary?

查看:44
本文介绍了在字典中获取最大值的键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字典:键是字符串,值是整数.

示例:

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

我想得到 'b' 作为答案,因为它是具有更高值的键.

我使用具有反向键值元组的中间列表执行了以下操作:

inverse = [(value, key) for key, value in stats.items()]打印最大值(逆)[1]

那是更好(或更优雅)的方法吗?

解决方案

你可以使用 operator.itemgetter :

导入操作符统计信息 = {'a':1000,'b':3000,'c': 100}max(stats.iteritems(), key=operator.itemgetter(1))[0]

使用 stats.iteritems() 代替在内存中构建新列表.max() 函数的 key 参数是一个计算用于确定如何对项目进行排名的键的函数.

请注意,如果您有另一个键值对 'd': 3000,该方法将只返回 一个 两个,即使它们都有最大值.

<预><代码>>>>进口经营者>>>统计 = {'a':1000, 'b':3000, 'c': 100, 'd':3000}>>>max(stats.iteritems(), key=operator.itemgetter(1))[0]'乙'

如果使用 Python3:

<预><代码>>>>max(stats.items(), key=operator.itemgetter(1))[0]'乙'

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(). The key parameter to the max() 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' 

If using Python3:

>>> max(stats.items(), key=operator.itemgetter(1))[0]
'b'

这篇关于在字典中获取最大值的键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆