How to switch dictionary keys and values in python ?

Created November 23, 2022 | Viewed 82 | by Benjamin Edit


Example of how to switch dictionary keys and values in python:

Switching dictionary keys and values

Let's consider the following dictionary:

d = {'A':1, 'B':2, 'C':3}

To iterate over all keys and values we can use items():

for x, y in d.items():
    print(x,y)

gives

A 1
B 2
C 3

Then to create a new dictionary with inverted keys and values a straigtforward solution is to do:

new_d = {y: x for x, y in d.items()}

gives

{1: 'A', 2: 'B', 3: 'C'}

Nested dictionaries

Another example: the goal is to switch keys and values of dictionaries inside another dictionary:

d = { 'table 1':{'A':1, 'B':2, 'C':3}, 'table 2':{'D':4, 'E':5, 'F':6} }

To iterate over all keys and values

for x, y in d.items():
    print(x,y)
    for xn, yn in y.items():
        print(xn,yn)

gives

table 1 {'A': 1, 'B': 2, 'C': 3}
A 1
B 2
C 3
table 2 {'D': 4, 'E': 5, 'F': 6}
D 4
E 5
F 6

then

new_d = { x: { yn:xn for xn, yn in y.items() } for x, y in d.items()  }

gives

{'table 1': {1: 'A', 2: 'B', 3: 'C'}, 'table 2': {4: 'D', 5: 'E', 6: 'F'}}

Example of use with a pandas dataframe

import pandas as pd

df = pd.DataFrame(data=['A','B','C'])

print(df)

gives

   0
0  A
1  B
2  C

d = {'A':100,'B':200,'C':300}

df.replace(d,inplace=True)

print(df)

gives

     0
0  100
1  200
2  300

new_d = {y: x for x, y in d.items()}

df.replace(new_d,inplace=True)

print(df)

gives

   0
0  A
1  B
2  C

See also