3dz Soft

Python – Search key in a Dictionary by value

by on Feb.13, 2012, under Code snippets

If you need to get the key of an item from a Dictionary in Python, supposing that the items are unique, here’s an easy way to do it:


def find_key(dic, val):
 """return the key of dictionary dic given the value"""
 return [k for k, v in dic.iteritems() if v == val][0]

where dic is the dictionary, and val is the value for  whose key you are looking for.

:

Leave a Reply

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!