17
votes

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):
    ??????
3

3 Answers

22
votes

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
5
votes

You can make a reverse dictionary:

revdict = dict((v,k) for k,v in ref.items())

then look up what you want:

assert revdict["def"] == "abc"

Note this won't work if two keys map to the same value.

2
votes
dict(map( lambda a:[a[1],a[0]], d.iteritems() ))