Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get dict key by max value [duplicate]

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?

like image 826
mclafee Avatar asked Dec 30 '12 14:12

mclafee


People also ask

Can key in dictionary have duplicate values?

First, a given key can appear in a dictionary only once. Duplicate keys are not allowed.

How do I return a key to the highest value in Python?

The simplest way to get the max value of a Python dictionary is to use the max() function. The function allows us to get the maximum value of any iterable.

How do you find the maximum value in a dictionary?

Use max() with the key parameter set to dict. get() to find and return the key of the maximum value in the given dictionary. Use min() with the key parameter set to dict. get() to find and return the key of the minimum value in the given dictionary.

Does Python dict allow duplicates?

Python dictionary doesn't allow key to be repeated. However, we can use defaultdict to find a workaround.


1 Answers

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.

like image 79
Martijn Pieters Avatar answered Oct 04 '22 19:10

Martijn Pieters