Swap keys and values in a Python dictionary
petercour
Posted on July 3, 2019
A dictionary is a one to one mapping. Every key has a value.
In Python that can be
dict = {'a': 1, 'b': 2, 'c': 3}
You can then get the values like this
print(dict['b'])
That's great and all. But what if you want to flip the entire dictionary? Where keys are values and values and keys.
Swap values
You can easily swap the key,dictionary pairs in Python, with a one liner.
dict = {value:key for key, value in dict.items()}
So in practice you can have something like this:
dict = {'a': 1, 'b': 2, 'c': 3}
print(dict)
dict = {value:key for key, value in dict.items()}
print(dict)
This will output
{'a': 1, 'c': 3, 'b': 2}
{1: 'a', 2: 'b', 3: 'c'}
So the one liner
dict = {value:key for key, value in dict.items()}
flipped the whole dictionary. Nice trick :)
Learn Python?
💖 💪 🙅 🚩
petercour
Posted on July 3, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.