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'}

+3 votes

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'}