Reverse the Keys and Values in a Dictionary in Python

Reversing the keys and values in a dictionary allows you to interchange their positions. In this blog post, we will explore different methods to reverse the keys and values in a dictionary in Python.

Method 1: Using dictionary comprehension

my_dict = {"a": 1, "b": 2, "c": 3}
reversed_dict = {value: key for key, value in my_dict.items()}

print("Reversed Dictionary:", reversed_dict)

Output:

Reversed Dictionary: {1: ‘a’, 2: ‘b’, 3: ‘c’}

Method 2: Using the zip() function

my_dict = {"a": 1, "b": 2, "c": 3}
reversed_dict = dict(zip(my_dict.values(), my_dict.keys()))

print("Reversed Dictionary:", reversed_dict)

Output:

Reversed Dictionary: {1: ‘a’, 2: ‘b’, 3: ‘c’}