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