1

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'}
Community
  • 1
  • 1
user1352521
  • 341
  • 1
  • 5
  • 8
  • 3
    irrelevant, but I still don't understand those people who downvote a user's legit confusion on some topic, even given his/her stack life has only been a month. – nye17 May 24 '12 at 01:33
  • 1
    Agreed. A downvote for a newcomers question should at least be accompanied by an explanation for the downvote and/or a suggestion on how to improve the question. – Joel Cornett May 24 '12 at 01:44
  • Sorry for the duplicate. I asked the wrong question. – user1352521 May 24 '12 at 01:52

3 Answers3

7

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'}
jamylak
  • 128,818
  • 30
  • 231
  • 230
mata
  • 67,110
  • 10
  • 163
  • 162
  • heh, exactly same answer. I had to go through the captcha check, that's why I'm late. I'll delete my answer. +1. – ch3ka May 24 '12 at 01:08
3

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'}
mhawke
  • 84,695
  • 9
  • 117
  • 138
3

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

John La Rooy
  • 295,403
  • 53
  • 369
  • 502