Possible Duplicate:
Python reverse / inverse a mapping
Say I have the following.
D = {'a':1,'b':2,'c':3}
How would I reverse each element so I get
inverseD = {1:'a',2:'b',3'c'}
Possible Duplicate:
Python reverse / inverse a mapping
Say I have the following.
D = {'a':1,'b':2,'c':3}
How would I reverse each element so I get
inverseD = {1:'a',2:'b',3'c'}
use a dict comprehension (Python 2.7+
and 3.0+
):
D = {'a':1,'b':2,'c':3}
inverse = {v: k for k, v in D.items()}
print(inverse)
# {1: 'a', 2: 'b', 3: 'c'}
For Python 2.6 and earlier (no dict comprehension):
d = {'a':1,'b':2,'c':3}
inverse_dict = dict((v,k) for k,v in d.items())
This assumes that the values of dict d
are hashable, for example, it won't work on this dictionary:
>>> d={'l':[],'d':{},'t':()}
>>> inverse_dict = dict((v,k) for k,v in d.items())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
You will also run into problems if the values of the original dict are not unique, e.g.
>>> d={'a': 1, 'c': 3, 'b': 2, 'd': 1}
>>> dict((v,k) for k,v in d.items())
{1: 'd', 2: 'b', 3: 'c'}
You can use mata's answer if you have Python2.7+ otherwise use mhawke's answer.
Inverting a dict like this only works properly if all the values of the source dict are unique and hashable
If the values are hashable, but not unique you can make a dict with having lists for the values instead