Get the key corresponding to the minimum value within a dictionary
If I have a Python dictionary, how do I get the key to the entry which contains the minimum value?
I was thinking about something to do with the min()
function...
Given the input:
{320:1, 321:0, 322:3}
It would return 321
.
Best: min(d, key=d.get)
-- no reason to interpose a useless lambda
indirection layer or extract items or keys!
>>> d = {320: 1, 321: 0, 322: 3}
>>> min(d, key=d.get)
321
Here's an answer that actually gives the solution the OP asked for:
>>> d = {320:1, 321:0, 322:3}
>>> d.items()
[(320, 1), (321, 0), (322, 3)]
>>> # find the minimum by comparing the second element of each tuple
>>> min(d.items(), key=lambda x: x[1])
(321, 0)
Using d.iteritems()
will be more efficient for larger dictionaries, however.
For multiple keys which have equal lowest value, you can use a list comprehension:
d = {320:1, 321:0, 322:3, 323:0}
minval = min(d.values())
res = [k for k, v in d.items() if v==minval]
[321, 323]
An equivalent functional version:
res = list(filter(lambda x: d[x]==minval, d))
min(d.items(), key=lambda x: x[1])[0]