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):
??????
1) Using OrderedDict() and items() method Later you make use of a reversed() function which is an in-built python method that takes an argument as the sequence data types like tuple, lists, dictionaries, etc and returns the reverse of it. Remember that reversed() method does not modify the original iterator.
The straight answer is NO. You can not have duplicate keys in a dictionary in Python.
Duplicate keys are not allowed in a Map.
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
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With