DEV Community

petercour
petercour

Posted on

4 1

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?

Heroku

Deploy with ease. Manage efficiently. Scale faster.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top 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.

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay