This post will discuss how to invert the mapping of a dictionary in Python, where all values in the dictionary are unique. The dictionary { k1: v1, k2: v2, … , kn: vn} should be transformed into a dictionary { v1: k1, v2: k2, … , vn: kn}.

1. Using Dictionary Comprehension

A simple solution to invert each key-value pair of a dictionary is using dictionary comprehension, which allows us to create a new dictionary by applying some condition on each key-value pair of an existing dictionary. Here is how we can use dictionary comprehension to invert mapping of a dictionary:

Download  Run Code

 
This method is concise and elegant, and works for any type of key-value pair. We can also use a dictionary constructor instead of dictionary comprehension. The dictionary constructor takes an iterable object (such as a list or a tuple) of key-value pairs as an argument and returns a new dictionary with those key-value pairs.

Download  Run Code

2. Using Dictionary Iterators

The fastest solution is to use dictionary iterators to iterate over the dictionary’s keys and create a new dictionary with reverse mapping. Here is how we can use dictionary iterators to invert mapping of a dictionary:

Download  Run Code

3. Using map() and reversed() functions

Another way to invert mapping of a dictionary in Python is using the map() and reversed() functions. The map() function provides a convenient way to apply a function to every item of an iterable and the reversed() function returns an iterator that yields the items in reverse order. They can be used as follows to inverse a dictionary:

Download  Run Code

 
If we need to modify the dictionary in-place rather than creating a new dictionary, we can create a copy of the dictionary and update it with value-key pairs. Here is an example of how to use these functions to create an inverse dictionary:

Download  Run Code

4. Using zip() function

A final way to invert mapping of a dictionary in Python is to use the zip() function with the dictionary constructor. The zip() function takes two or more iterable objects and yields tuples containing corresponding items from each iterable. Here is an example of its usage to invert mapping of a dictionary:

Download  Run Code

How to handle duplicates?

If the dictionary’s values aren’t unique, we can use a simple for-loop to handle duplicate values in a dictionary. This is demonstrated below:

Download  Run Code

That’s all about inverting the mapping of a dictionary in Python.