8
votes

Possible Duplicate:
Getting key with maximum value in dictionary?

Let's say I have a dictionary that is comprised of integer keys and integer values. I want to find the integer key with the highest corresponding value. Is there any built in method to do something like this or do I need to implement some kind of merge/sort algorithm?

2
Already answered on StackOverflow here - Ray Toal
Have tried to find an existing answer? See this: stackoverflow.com/questions/268272/… - the solution is just this: max(stats.iteritems(), key=operator.itemgetter(1)) - Tadeck
max(stats, key=stats.itemgetter(1)) is the most voted from stackoverflow.com/questions/268272/… - jimifiki

2 Answers

42
votes

You can just use max

>>> x = {1:2, 3:6, 5:4}
>>> max(x, key=lambda i: x[i])
3

Or just:

>>> max(x, key=x.get)
3
5
votes

There are methods to do that, and preferred way is to use this:

import operator

result = max(your_dict.iteritems(), key=operator.itemgetter(1))[0]

Note, that for your needs operator.itemgetter(1) could be replaced by lambda x: x[1].