Getting key with maximum value in dictionary?

2018-12-31 03:01发布

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?

20条回答
看风景的人
2楼-- · 2018-12-31 03:37

Per the iterated solutions via comments in the selected answer...

In Python 3:

max(stats.keys(), key=(lambda k: stats[k]))

In Python 2:

max(stats.iterkeys(), key=(lambda k: stats[k]))
查看更多
忆尘夕之涩
3楼-- · 2018-12-31 03:40

How about:

 max(zip(stats.keys(), stats.values()), key=lambda t : t[1])[0]
查看更多
高级女魔头
4楼-- · 2018-12-31 03:41
d = {'A': 4,'B':10}

min_v = min(zip(d.values(), d.keys()))
# min_v is (4,'A')

max_v = max(zip(d.values(), d.keys()))
# max_v is (10,'B')
查看更多
听够珍惜
5楼-- · 2018-12-31 03:42

Here is another one:

stats = {'a':1000, 'b':3000, 'c': 100}
max(stats.iterkeys(), key=lambda k: stats[k])

The function key simply returns the value that should be used for ranking and max() returns the demanded element right away.

查看更多
何处买醉
6楼-- · 2018-12-31 03:43

Given that more than one entry my have the max value. I would make a list of the keys that have the max value as their value.

>>> stats = {'a':1000, 'b':3000, 'c': 100, 'd':3000}
>>> [key for m in [max(stats.values())] for key,val in stats.iteritems() if val == m]
['b', 'd']

This will give you 'b' and any other max key as well.

Note: For python 3 use stats.items() instead of stats.iteritems()

查看更多
宁负流年不负卿
7楼-- · 2018-12-31 03:45

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'
查看更多
登录 后发表回答