Feed on

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

Bookmark and Share

if that was helpful ...

check out the other tips and tricks i've compiled on these pages. you might learn something else interesting!

Did I get this wrong? Let me know!

Trackback URI | Comments RSS

More blogs about http://desk.stinkpot.org:8080/tricks.