views:

67

answers:

3

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" from "abc"?

def revmapper(to):
    ???
+1  A: 

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
+5  A: 

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
Just to be clear, this wouldn't be possible with this dict `d = {'a':[1, 2, 3]}`
razpeitia
@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
A: 
dict(map( lambda a:[a[1],a[0]], d.iteritems() ))
eruciform
There is no reason to use map+lambda ever. See the other solutions for how to build a list comprehension or generator expression.
Aaron Gallagher
@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
@eruciform, 1) no function call overhead. 2) much, much easier to read, especially when there's unpacking involved.
Aaron Gallagher
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