How to reverse or invert a dictionary mapping with Python?

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.