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.
I wrote this with the help of cycle 'for' and method '.get()' and I changed the name 'map' of the dictionary to 'map1' because 'map' is a function.
If values aren't unique AND may be a hash (one dimension):
And with a recursion if you need to dig deeper then just one dimension:
As per my comment to the question. I think the easiest and one liner which works for both Python2 and Python 3 will be
If the values in
my_map
aren't unique:Combination of list and dictionary comprehension. Can handle duplicate keys