Send As SMS

9/21/2006

find the key for the minimum (or maximum) value in a python dict

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


0 Comments:

Post a Comment

Links to this post:

Create a Link

<< Home

My blog has moved! Redirecting...

You should be automatically redirected. If not, visit http://stinkpot.afraid.org:8080/tricks/ and update your bookmarks.