Swap keys and values in a Python dictionary

petercour

petercour

Posted on July 3, 2019

Swap keys and values in a Python dictionary

dictionary

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}
Enter fullscreen mode Exit fullscreen mode

You can then get the values like this

print(dict['b'])
Enter fullscreen mode Exit fullscreen mode

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()}
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

This will output

{'a': 1, 'c': 3, 'b': 2}
{1: 'a', 2: 'b', 3: 'c'}
Enter fullscreen mode Exit fullscreen mode

So the one liner

dict = {value:key for key, value in dict.items()}
Enter fullscreen mode Exit fullscreen mode

flipped the whole dictionary. Nice trick :)

Learn Python?

💖 💪 🙅 🚩
petercour
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.

Related