8

Given a dictionary d where the key values pair consist of a string as key and an integer as value, I want to print the key string where the value is the maximum.

Of course I can loop over d.items(), store the maximum and its key and output the latter after the for loop. But is there a more "pythonic" way just using just a max function construct like

print max(...)
halloleo
  • 9,216
  • 13
  • 64
  • 122
  • Depending on your usage of the dict you might want to switch key and value, having the integer has key an dstring has value... (Of course you can do this if you never use the string key...) – JC Plessis Sep 13 '12 at 09:01
  • 3
    Swappping key and value is *not* a good idea, because the values might not at all be unique... – halloleo Sep 13 '12 at 12:50

1 Answers1

16
print max(d.keys(), key=lambda x: d[x]) 

or even shorter (from comment):

print max(d, key=d.get)
Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175
  • 6
    how about `max(d, key=d.get)` – georg Sep 13 '12 at 08:30
  • Both seem to work! :-) Thanks for this: I suspected that python might offer a concise way to deal with this problem! - In regards to both solutions, the second version looks to me is easier to remember. Does it have any caveats over the first one? – halloleo Sep 13 '12 at 12:47
  • @halloleo I don't think it does. `keys()` is just redundant, `get` is a method whose behavior only differs from the `lambda` for items not present in the dict, which won't happen in this case. – Lev Levitsky Sep 13 '12 at 13:02