Skip to content

Instantly share code, notes, and snippets.

@chroto
Created July 13, 2012 20:06
Show Gist options
  • Save chroto/3107078 to your computer and use it in GitHub Desktop.
Save chroto/3107078 to your computer and use it in GitHub Desktop.
Find a dict key from its value
def reverse_dict_lookup(d, val):
"""
Performs a reverse lookup on a dictionary object, raising ValueError on
failure.
>>> reverse_dict_lookup({'a': 1, 'b': 2, 'c': 3}, 2)
'b'
>>> reverse_dict_lookup({}, 'a')
Traceback (most recent call last):
...
ValueError
"""
try:
return (key for key, value in d.items() if value == val).next()
except StopIteration:
raise ValueError
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment