Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reverse mapping of dictionary with Python [duplicate]

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):
    ??????
like image 359
prosseek Avatar asked Jul 11 '10 01:07

prosseek


People also ask

Can you reverse a dictionary Python?

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.

Can dictionary have duplicate values Python?

The straight answer is NO. You can not have duplicate keys in a dictionary in Python.

Can map have duplicate keys Python?

Duplicate keys are not allowed in a Map.


2 Answers

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
like image 73
Stephen Avatar answered Sep 17 '22 17:09

Stephen


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.

like image 40
Ned Batchelder Avatar answered Sep 19 '22 17:09

Ned Batchelder