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?
Top comments (2)
Keep in mind that his can fail if the value is non hashable.
:-)
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.