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])
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])
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)
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]