python

Pandas dataframe to dictionary conversion python

Pandas Dataframe provides multiple methods to convert Dataframe to python dictionary. We are listing them one by one with descriptions.

import pandas as pd

data = {
  'name': ['Rick', 'Carol', 'Carl', 'Negan'],
  'place': ['Alexendria', 'Kingdom', 'Alexendria', 'Saviours']
} 
df = pd.DataFrame.from_dict(data)
print(df)
#     name      place
# 0   Rick      Alexendria
# 1   Carol     Kingdom
# 2   Carl      Alexendria
# 3   Negan     Saviours

# Get dict from dataframe(Method 1)
dict1 = dict(df.values)
print(dict1)
# -> {'Rick': 'Alexendria', 'Carol': 'Kingdom', 'Carl': 'Alexendria', 'Negan': 'Saviours'}

# Get dict from dataframe(Method 2)
dict2 = df.to_dict('index')
print(dict2)
# -> {0: {'name': 'Rick', 'place': 'Alexendria'}, 1: {'name': 'Carol', 'place': 'Kingdom'}, 2: {'name': 'Carl', 'place': 'Alexendria'}, 3: {'name': 'Negan', 'place': 'Saviours'}}
Was this helpful?