Tech Chorus

How To Interchange Values And Keys Of A Dictionary In Python?

written by Sudheer Satyanarayana on 2015-12-09

Here's our sample dictionary:

my_dict = {'game': 'cricket', 'planet': 'earth'} The values() method of the dictionary returns a list of values.

>>> my_dict.values()
['earth', 'cricket']

The keys() method of the dictionary returns a list of keys.

>>> my_dict.keys()
['planet', 'game']

Notice the 1-1 correspondence between the items of the returned lists. This correspondence remains unchanged if the dictionary is unchanged.

To interchange the keys and values all you have to do is zip and generate another dictionary. Let's complete the remaining steps.

zip(my_dict.values(), my_dict.keys())
[('earth', 'planet'), ('cricket', 'game')]

Now, we have a list of tuples. Each tuple contains the value and key pairs. The last step is to create a dictionary using this list. Pass the above list to the built-in function dict().

>>> dict(zip(my_dict.values(), my_dict.keys()))
{'earth': 'planet', 'cricket': 'game'}

Here's a one-liner to summarize the concept.

dict(zip(my_dict.values(), my_dict.keys()))