patternpythonCriticalCanonical
Getting key with maximum value in dictionary?
Viewed 0 times
keywithdictionarygettingmaximumvalue
Problem
I have a dictionary where keys are strings, and values are integers.
How do I get the key with the maximum value? In this case, it is
Is there a nicer approach than using an intermediate list with reversed key-value tuples?
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
And instead of building a new list in memory use
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.
If using Python3:
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.