reverse mapping of dictionary with Python

dictionary, python

Solution

If you do this often, you'll want to build a reverse dictionary:

>>> rev_ref = dict((v,k) for k,v in ref.iteritems())
>>> rev_ref
{'def': 'abc'}

>>> def revmapper(to):
...    return rev_ref[to]

If it's rare, and you don't care if it's inefficient, do this:

>>> def revmapper(to):
...    for k,v in ref.iteritems():
...      if v == to: return k

Problem

Possible Duplicate: Inverse dictionary lookup - Python If I have a dictionary named ref as follows ``` ref = {} ref["abc"] = "def" ``` I can get "def" from "abc" ``` def mapper(from): return ref[from] ``` But, how can I get from "def" to "abc"? ``` def revmapper(to): ?????? ```

Original source

Related problems