find the key for the minimum (or maximum) value in a python dict
September 21st, 2006 by Lawrence David
the trouble with dicts or hashes is that there’s no easy way to search for a value and return a key.
for instance, i’m not aware of a simple python command to find the dict key associated with the smallest value in the dict.
nevertheless, there are quick and dirty ways to pull off the above job.
take dictionary a:
>>> a_dict = {“me”: 5, “you”: 6, “she”:200}
to find the key associated with the minimum value, we can “flip” the dictionary (assuming there are no duplicate values):
>>> b_dict = dict(map(lambda item: (item[1],item[0]),a_dict.items()))
now, we use the min (or max) built-in function to find the smallest (or largest) value:
>>> print b[min(b.keys())]