Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
2 views
in Python by (580 points)

I have this dictionary:

map_old = { 'p': 8, 'q':9 }

How can I invert this map to get:

 

map_inv = { 8: 'p', 9: 'q' } 

1 Answer

0 votes
by (10.9k points)
edited by

There are various ways of doing this, some of them are a follows:

1. Inverting with map and reversed

map_inv = dict(map(reversed,map_old.items()))

2.Inverting with a comprehension

For Python 2.7.x use:

map_inv = {v: k for k, v in map_old.iteritems()} 

For Python 3 and higher version use:

map_inv = {v: k for k, v in map_old.items()}

3.Inverting with a Defaultdict

 from collections import defaultdict

map_inv = defaultdict(list)

{map_inv[v].append(k) for k, v in map_old.items()}

4.Inverting with a for loop:

map_inv = dict()

for key, value in map_old.items():

map_inv.setdefault(value, list()).append(key)

 

The preferable way is by using the dictionary comprehension but it has a constraint that it cannot work with non-unique values. So, if you are working with non-unique values then refer to the other methods.

Hope it helps!

If you are looking for upskilling yourself in python you can join our Python Certification and learn from an industry expert.

Related questions

0 votes
1 answer
asked Jul 3, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
asked Jan 2, 2021 in Python by laddulakshana (16.4k points)
0 votes
1 answer
asked Oct 30, 2020 in Python by Sudhir_1997 (55.6k points)
0 votes
1 answer
asked Jul 13, 2020 in Python by ashely (50.2k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...