Categories
Python Answers

How to reverse or invert a dictionary mapping with Python?

Spread the love

Sometimes, we want to reverse or invert a dictionary mapping with Python.

In this article, we’ll look at how to reverse or invert a dictionary mapping with Python.

How to reverse or invert a dictionary mapping with Python?

To reverse or invert a dictionary mapping with Python, we can use the items method of the dictionary to get the items and then use dictionary comprehension to flip the keys and values.

For instance, we write:

my_map = {'a': 1, 'b': 2}
inv_map = {v: k for k, v in my_map.items()}
print(inv_map)

We call my_map.items to return the key and value of each entry as k and v respectively.

Then we flip them by putting v to the left of the colon and k after.

And then we assign the returned dictionary to inv_map.

Therefore, inv_map is {1: 'a', 2: 'b'}.

Conclusion

To reverse or invert a dictionary mapping with Python, we can use the items method of the dictionary to get the items and then use dictionary comprehension to flip the keys and values.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *