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 04:03

Thanks, very elegant, I didn't remember that max allows a "key" parameter.

BTW, to get the right answer ('b') it has to be:

import operator
stats = {'a':1000, 'b':3000, 'c': 100}
max(stats.iteritems(), key=operator.itemgetter(1))[0]
查看更多
忆尘夕之涩
3楼-- · 2018-12-31 04:03

A heap queue is a generalised solution which allows you to extract the top n keys ordered by value:

from heapq import nlargest

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

res1 = nlargest(1, stats, key=stats.__getitem__)  # ['b']
res2 = nlargest(2, stats, key=stats.__getitem__)  # ['b', 'a']

res1_val = next(iter(res1))                       # 'b'

Note dict.__getitem__ is the method called by the syntactic sugar dict[]. As opposed to dict.get, it will return KeyError if a key is not found, which here cannot occur.

查看更多
登录 后发表回答