Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k 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 (106k 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
4 answers
0 votes
1 answer
0 votes
1 answer
asked Oct 10, 2019 in Python by Sammy (47.6k points)

Browse Categories

...