# Getting key with maximum value in dictionary?

1 view
in Python

I have a dictionary: keys are strings, values are integers.

Example:

stats = {'p':4000, 'q':8000, 'r': 900}

I'd like to get 'q' 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)

Is that one the better (or even more elegant) approach?

by (10.9k points)
edited

You can use the operator.itemgetter(items) ,it returns a callable object which fetches item from its operand using _getitem_() method of the operand.

To use operator.itemgetter() use this code:

import operator

stats = {'p':4000, 'q':8000, 'r': 900}

max(stats.iteritems(), key=operator.itemgetter(1))

In the above max() function, you have the “key” parameter is a function which compares elements to find the maximum between them. You may also use stats.iteritems() since it minimizes the memory use by eliminating the need for creating a new list.

Note:

In case you have:

stats = {'p':4000, 'q':8000, 'r': 900,‘s’:8000}

Then don’t expect the function to return both the maximum values ‘q’ and ‘s’,it will only return either of the two i.e, either ‘q’ or ‘s’ and not both.

Ex-

>>> import operator

>>> stats = {'p':4000, 'q':8000, 'r': 900,‘s’:8000}

>>> max(stats.iteritems(), key=operator.itemgetter(1))

's’

For Python 3, replace stats.iteritems() with stats.items().

Hope this helps!

by (20.3k points)

You can try using the code given below:

max(stats, key=stats.get)

OR

You can just try doing this:

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

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

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