4

This gives the max value in a dict, but how do I get the dict key for the max value?

max([d[i] for i in d])
Baz
  • 12,713
  • 38
  • 145
  • 268
  • 3
    NB `max(d[i] for i in d)` is conceptually simpler (and more memory-efficient) and `max(d.values())` is clearer IMHO. –  Dec 02 '12 at 13:06

2 Answers2

15

Use the key= keyword argument to max():

max(d, key=lambda k: d[k])

Instead of the lambda you can use operators.itemgetter as well:

import operators
max(d, key=operators.itemgetter(d))

or pass in d.get:

max(d, key=d.get)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

Assuming it's safe to use == for comparison in this case, which might not always be true e.g. with floats.

d = { 'a' : 2, 'b' : 2, 'c' : 1}

max_val = max(d.values())
max_keys = [k for k, v in d.items() if v == max_val]

print(max_keys)

gives,

['a', 'b']

[Program finished]
Subham
  • 397
  • 1
  • 6
  • 14