How to Reverse a Dictionary in Python?

In this tutorial, I will explain how to reverse a dictionary in Python. Recently in a Python webinar, someone asked me a question about reversing a dictionary, then I explored more about this topic and found several effective ways to achieve this task. I will share my findings with examples and screenshots of executed example code.

Reverse a Dictionary in Python

Let’s say you have a dictionary of US state capitals like this:

state_capitals = {
    'California': 'Sacramento',
    'New York': 'Albany',
    'Texas': 'Austin',
    'Florida': 'Tallahassee'
}

But for some reason, you need to look up states by their capital cities instead. Reversing the dictionary would give you:

capital_states = {
    'Sacramento': 'California',
    'Albany': 'New York',    
    'Austin': 'Texas',
    'Tallahassee': 'Florida'
}

Now you can easily find which state a capital belongs to, like capital_states['Austin'] would return 'Texas'.

Read How to Create a Dictionary from a List in Python?

1. Use a For Loop to Reverse a Dictionary

One way to reverse a Python dictionary is to use a for loop. Here are the steps:

  1. Create a new empty dictionary to store the reversed key-value pairs
  2. Loop through each key-value pair in the original dictionary
  3. Add the value as the key and the key as the value in the new dictionary

Here’s how that looks in the code:

state_capitals = {
    'California': 'Sacramento',
    'New York': 'Albany',
    'Texas': 'Austin', 
    'Florida': 'Tallahassee'
}

capital_states = {}
for state, capital in state_capitals.items():
    capital_states[capital] = state

print(capital_states)

This will output:

{'Sacramento': 'California', 'Albany': 'New York', 'Austin': 'Texas', 'Tallahassee': 'Florida'}  

I executed the above example code and added the screenshot below.

Reverse a Dictionary in Python

Reversing a dictionary by swapping its keys and values can be achieved using a for loop, as demonstrated in the provided example. This method creates a new dictionary where each original value becomes a key, and each original key becomes its corresponding value.

Check out How to Convert Tuple to Dict in Python?

2. Use a Dictionary Comprehension

Another concise way to reverse a dictionary is by using Python dictionary comprehension. This condenses the for loop into a single expression:

state_capitals = {
    'California': 'Sacramento', 
    'New York': 'Albany',
    'Texas': 'Austin',
    'Florida': 'Tallahassee' 
}

capital_states = {capital: state for state, capital in state_capitals.items()}

print(capital_states)  

This will output:

{'Sacramento': 'California', 'Albany': 'New York', 'Austin': 'Texas', 'Tallahassee': 'Florida'}  

I executed the above example code and added the screenshot below.

How to Reverse a Dictionary in Python

Utilizing dictionary comprehension offers a concise method to reverse key-value pairs in a dictionary. This approach efficiently creates a new dictionary by swapping keys and values in a single line of code. However, ensure that the original dictionary’s values are unique and hashable to serve as valid keys in the reversed dictionary.

Read How to Convert Dict to String Python

Deal with Duplicate Values

When reversing a dictionary, it’s crucial to handle scenarios where multiple keys share the same value, as Python dictionaries cannot have duplicate keys. In such cases, the reversed dictionary should map each original value to a list of keys that had that value. This ensures that all associations are preserved without data loss.

For example:

from collections import defaultdict

# Original dictionary with duplicate values
state_capitals = {
    'California': 'Sacramento',
    'Nevada': 'Carson City',
    'Oregon': 'Salem',
    'New York': 'Albany',
    'Texas': 'Austin',
    'Florida': 'Tallahassee',
    'Georgia': 'Atlanta',
    'Illinois': 'Springfield',
    'Massachusetts': 'Boston',
    'New Hampshire': 'Concord',
    'New Jersey': 'Trenton',
    'New Mexico': 'Santa Fe',
    'New York': 'Albany',  # Duplicate value
    'Texas': 'Austin',     # Duplicate value
}

# Reversing the dictionary
capital_states = defaultdict(list)
for state, capital in state_capitals.items():
    capital_states[capital].append(state)

print(dict(capital_states))

Output:

{
    'Sacramento': ['California'],
    'Carson City': ['Nevada'],
    'Salem': ['Oregon'],
    'Albany': ['New York'],
    'Austin': ['Texas'],
    'Tallahassee': ['Florida'],
    'Atlanta': ['Georgia'],
    'Springfield': ['Illinois'],
    'Boston': ['Massachusetts'],
    'Concord': ['New Hampshire'],
    'Trenton': ['New Jersey'],
    'Santa Fe': ['New Mexico']
}

In this example, the defaultdict from the collections module is used to handle multiple keys mapping to the same value. Each value in the original dictionary becomes a key in the new dictionary, and the associated value is a list of all original keys that share this value.

Check out How to Convert Dict_Values to List in Python

Conclusion

In this article, I helped you to understand how to reverse a dictionary in Python. I explained two methods to accomplish this task such as using a for loop to reverse a dictionary and using a dictionary comprehension. I also discussed how to deal with duplicate values.

You may also read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.