18

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):
    ??????
Community
  • 1
  • 1
prosseek
  • 182,215
  • 215
  • 566
  • 871

3 Answers3

23

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
Stephen
  • 47,994
  • 7
  • 61
  • 70
  • 2
    Just to be clear, this wouldn't be possible with this dict `d = {'a':[1, 2, 3]}` – razpeitia Jul 11 '10 at 01:55
  • 2
    @razpeitia : For the reverse dictionary, that's true, but it would work with `d = {'a':(1,2,3)}`, and it wouldn't work if multiple keys had the same values... using the inefficient method will always, unfortunately - inefficiently. – Stephen Jul 11 '10 at 02:03
6

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.

Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
2
dict(map( lambda a:[a[1],a[0]], d.iteritems() ))
eruciform
  • 7,680
  • 1
  • 35
  • 47
  • There is no reason to use map+lambda ever. See the other solutions for how to build a list comprehension or generator expression. – habnabit Jul 11 '10 at 02:42
  • @aaron: what's the reason that map+lambda is inferior to the others? i assume there's some internal optimizations going on that make it different? how is (k,v)for... better than map(lambda... ? – eruciform Jul 11 '10 at 17:05
  • 1) no function call overhead. 2) much, much easier to read, especially when there's unpacking involved. – habnabit Jul 11 '10 at 21:30
  • cool, thanks. but regarding "no reason to use map+lambda ever", do you mean just in this case, or is this a general case? is there anything that "statement for array" can't do that map(lambda) can? – eruciform Jul 11 '10 at 21:35