0 votes
1 view
in Python by (47.8k points)

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' }

1 Answer

0 votes
by (107k points)

To do reverse / invert a mapping in Python 2.7.x you can use the following piece of code:-

my_map = { 'a': 1, 'b':2 }

inv_map = {x: i for i, x in my_map.iteritems()}

Print inv_map

image

If you want to do reverse / invert a mapping you can use the following piece of code:-

my_map = { 'a': 1, 'b':2 }

inv_map = {x: i for i, x in my_map.items()}

print(inv_map)

image

Related questions

+1 vote
1 answer
asked Jun 27, 2019 in Python by aghosh578 (580 points)
0 votes
1 answer
asked Oct 10, 2019 in Python by Sammy (47.8k points)
0 votes
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...