DEV Community

petercour
petercour

Posted on

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}

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?

Latest comments (2)

Collapse
 
rhymes profile image
rhymes • Edited

Keep in mind that his can fail if the value is non hashable.

>>> dict = { 1: [2] }
>>> {value:key for key, value in dict.items()}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <dictcomp>
TypeError: unhashable type: 'list'

:-)

All mutable data structures in Python are not hashable

Some comments may only be visible to logged-in visitors. Sign in to view all comments.