+1 vote
in Programming Languages by (40.5k points)

I want to swap keys and values in a Python dictionary. What is the pythonic way to do this?

E.g. 

{'a': 1, 'b': 2, 'c': 3, 'd': 4}

to

{1: 'a', 2: 'b', 3: 'c', 4: 'd'}

1 Answer

+3 votes
by (355k points)
selected by
 
Best answer

You can swap keys and values in a python dictionary using one line of code.

Here is an example to show how to swap keys and values:

>>> aa={'a':1,'b':2,'c':3,'d':4}
>>> aa
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
>>> swap_aa = {v:k for k,v in aa.items()}

swap_aa will look like the following:

>>> swap_aa
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}


...