9

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?

Community
  • 1
  • 1
user1427661
  • 11,158
  • 28
  • 90
  • 132
  • Already answered on StackOverflow [here](http://stackoverflow.com/a/1747244/831878) – Ray Toal Sep 22 '12 at 04:56
  • 1
    Have tried to find an existing answer? See this: http://stackoverflow.com/questions/268272/getting-key-with-maximum-value-in-dictionary - the solution is just this: `max(stats.iteritems(), key=operator.itemgetter(1))` – Tadeck Sep 22 '12 at 04:56
  • max(stats, key=stats.itemgetter(1)) is the most voted from http://stackoverflow.com/questions/268272/getting-key-with-maximum-value-in-dictionary – jimifiki Sep 22 '12 at 04:58

2 Answers2

42

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
georg
  • 211,518
  • 52
  • 313
  • 390
verdesmarald
  • 11,646
  • 2
  • 44
  • 60
5

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].

Tadeck
  • 132,510
  • 28
  • 152
  • 198
  • Is there some advantage to using `your_dict.iteritems()` over just `your_dict`? – verdesmarald Sep 22 '12 at 05:03
  • @verdesmarald: They give different results (`your_dict.iteritems()` returns something else than `your_dict`), so they are not comparable. – Tadeck Sep 22 '12 at 05:05
  • Sorry, I meant for this particular question, where `max(your_dict.iteritems())[0]` gives the same result as just `max(your_dict)`. – verdesmarald Sep 22 '12 at 05:09
  • @verdesmarald: You are incorrect - `max(your_dict)` will give you the biggest key, not the key corresponding to the biggest value. To see the difference, take a look at the result of this: `max({1:100,2:20})` (it will give you `2` instead of `1`). – Tadeck Sep 22 '12 at 05:26