Get dict key by max value
Question:
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?
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.
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?
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.