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.

4/22/2017 2:21:57 PM

Accepted Answer

Best: min(d, key=d.get) -- no reason to interpose a useless lambda indirection layer or extract items or keys!

7/19/2010 4:21:26 PM

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow