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?
First, a given key can appear in a dictionary only once. Duplicate keys are not allowed.
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.
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.
Python dictionary doesn't allow key to be repeated. However, we can use defaultdict to find a workaround.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With