How to Reverse a Dictionary in Python
Last Updated :
10 Jan, 2025
Improve
Reversing a dictionary typically means swapping the keys and values, where the keys become the values and the values become the keys. In this article, we will explore how to reverse a dictionary in Python using a variety of methods.
Using Dictionary Comprehension
Dictionary comprehension is a concise way to swap key and values by creating a new dictionary.
d1 = {'a': 1, 'b': 2, 'c': 3}
# Reverse the dictionary using dictionary comprehension
d2 = {v: k for k, v in d1.items()}
print(d2)
Output
{1: 'a', 2: 'b', 3: 'c'}
Explanation:
- We use the items() method to iterate over each key-value pair in the original dictionary.
- For each pair, we create a new dictionary where the value becomes the key and the key becomes the value.
Let's explore other methods of reversing a dictionary in python:
Table of Content
Using zip() Function
We can use Python’s built-in zip() function to reverse a dictionary. zip() function can combine two sequences (keys and values) into pairs, which can then be converted back into a dictionary.
d1 = {'a': 1, 'b': 2, 'c': 3}
# Reverse the dictionary using zip
d2 = dict(zip(d1.values(), d1.keys()))
print(d2)
Output
{1: 'a', 2: 'b', 3: 'c'}
Explanation:
- The
zip()
function pairs the values ofd1.values()
with the keys ofd1.keys()
. - The result is a series of tuples that are converted back into a dictionary using the
dict()
constructor.
Using a Loop
We can also reverse a dictionary using a simple loop, which gives you more control over the process if needed.
d1 = {'a': 1, 'b': 2, 'c': 3}
d2 = {}
# Loop through the dictionary and swap keys and values
for key, value in d1.items():
d2[value] = key
print(d2)
Output
{1: 'a', 2: 'b', 3: 'c'}
Explanation:
- We iterate over each key-value pair in the original dictionary.
- In each iteration, we assign the value as the new key in the reversed dictionary and the key as the value.