HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonCritical

Getting key with maximum value in dictionary?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
keyvaluegettingmaximumdictionarywith

Problem

I have a dictionary where keys are strings, and values are integers.

stats = {'a': 1, 'b': 3000, 'c': 0}


How do I get the key with the maximum value? In this case, it is 'b'.

Is there a nicer approach than using an intermediate list with reversed key-value tuples?

inverse = [(value, key) for key, value in stats.items()]
print(max(inverse)[1])

Solution

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'

Code Snippets

import operator
stats = {'a': 1000, 'b': 3000, 'c': 100}
max(stats.iteritems(), key=operator.itemgetter(1))[0]
>>> import operator
>>> stats = {'a': 1000, 'b': 3000, 'c': 100, 'd': 3000}
>>> max(stats.iteritems(), key=operator.itemgetter(1))[0]
'b'
>>> max(stats.items(), key=operator.itemgetter(1))[0]
'b'

Context

Stack Overflow Q#268272, score: 776

Revisions (0)

No revisions yet.