Given a dictionary like so:
my_map = { 'a': 1, 'b':2 }
How can one invert this map to get:
inv_map = { 1: 'a', 2: 'b' }
EDITOR NOTE: map
changed to my_map
to avoid conflicts with the built-in function, map
. Some comments may be affected below.
Using zip
I would do it that way in python 2.
This is not the best solution, but it works. Let's say the dictionary we want to reverse is:
dictionary = {'a': 1, 'b': 2, 'c': 3}, then:
The output of reverse_dictionary, should be {1: 'a', 2: 'b', 3: 'c'}
Assuming that the values in the dict are unique:
Try this for python 2.7/3.x
this code do like this: