36

I'm trying to get the dict key whose value is the maximum of all the dict's values.

I found two ways, both not elegant enough.

d= {'a':2,'b':5,'c':3}
# 1st way
print [k for k in d.keys() if d[k] == max(d.values())][0]
# 2nd way
print Counter(d).most_common(1)[0][0]

Is there a better approach?

aschultz
  • 1,658
  • 3
  • 20
  • 30
mclafee
  • 1,406
  • 3
  • 18
  • 25

1 Answers1

99

Use the key parameter to max():

max(d, key=d.get)

Demo:

>>> d= {'a':2,'b':5,'c':3}
>>> max(d, key=d.get)
'b'

The key parameter takes a function, and for each entry in the iterable, it'll find the one for which the key function returns the highest value.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • What if there are multiple keys? Can I pass, say, `len` to get the longest key with the most value? – SiddharthaRT Oct 30 '14 at 06:07
  • 1
    @SiddharthaRT: you can use a `lambda` for the key: `max(d, key=lamda k: (d[k], len(k)))` will return the key with the highest value, and if there is more than one such key, it'll be the longest key of those that is returned. – Martijn Pieters Oct 30 '14 at 07:37
  • How would you do if you wanted not just the key with the max value, but if you wanted the first n keys with the first n max values in the dict? – Tropilio May 01 '20 at 11:20
  • @Tropilio then use [`heapq.nlargest()`](https://docs.python.org/3/library/heapq.html#heapq.nlargest). – Martijn Pieters May 02 '20 at 00:10