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 dictionary comprehension.

For instance, we write

inv_map = {v: k for k, v in my_map.items()}

to flip the key k and value v with v: k for k, v in my_map.items().

We get the key-value pairs with items.

Conclusion

To reverse or invert a dictionary mapping with Python, we can use dictionary comprehension.

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 *