To invert a dictionary and swap the keys and values of a dictionary in Python, use dictionary comprehension and swap the keys and values.

d = {"name":"Bobby", "age":20,"height":65}

d_inverted = {value: key for key, value in d.items()}

print(d_inverted)

#Output:
{'Bobby': 'name', 20: 'age', 65: 'height'}

When working with dictionaries in Python, the ability to modify your variables to get new values easily is valuable.

One such situation is if you want to invert a dictionary variable. Inverting a dictionary means swapping the keys and values so the values with become the new keys and the keys will become the new values.

To invert a dictionary, you can use dictionary comprehension.

Below is a simple example showing you how to invert a dictionary with Python.

d = {"name":"Bobby", "age":20,"height":65}

d_inverted = {value: key for key, value in d.items()}

print(d_inverted)

#Output:
{'Bobby': 'name', 20: 'age', 65: 'height'}

Performing Reverse Dictionary Lookup After Inverting Dictionary in Python

One case where inverting a dictionary might be useful is if you want to perform a reverse dictionary lookup, i.e. you want to find a key based on a specific value.

You can perform reverse dictionary lookups by inverting the dictionary you are working with and then getting the key you want directly via the value.

After inverting your dictionary, just access the dictionary key/value pair with the value you are looking for.

Below is a simple example showing you how to invert a dictionary and perform a reverse lookup after inversion with Python.

d = {"name":"Bobby", "age":20,"height":65}

d_inverted = {value: key for key, value in d.items()}

print(d_inverted["Bobby"])

#Output:
name

Inverting Dictionary to Remove Duplicate Values from Dictionary in Python

One other use where inverting a dictionary might be useful is if you want to remove duplicate values from a dictionary.

Since dictionaries can only have a unique set of keys, when you go to invert it, you will remove any duplicate values.

Below is an example of inverting a dictionary with duplicate values. You can see that only one key is kept for each value.

d = {"name":"Bobby", "age":20, "credits":20, "height":65, "weight":65, "income":65}

d_inverted = {value: key for key, value in d.items()}

#Output:
{'Bobby': 'name', 20: 'credits', 65: 'income'}

Hopefully this article has been useful for you to learn how to invert dictionary variables in Python.

Categorized in:

Python,

Last Update: March 22, 2024