← Go Back
If you want to swap
How to Reverse Keys and Values in a Dictionary
# Original dictionary.
d = {"a": 1, "b": 2, "c": 3}
# Dictionary with keys exchanged with values.
d2 = {v: k for k, v in d.items()}
print(d2) # {1: 'a', 2: 'b', 3: 'c'}
If you want to swap
d
in-place, you might use as well:# No need to create a copy.
d = {v: k for k, v in d.items()}
🐍 You might also find interesting: