python

Convert pandas DataFrame to python collection - dictionary

You can convert pandas data frame to python dictionary using to_dict() method. There are many parameters you can pass to this method to get the desired format of the dictionary.

import pandas as pd

df = pd.DataFrame()
df["Name"] = ["John", "Mark", "Rick"]
df["Score"] = [20, 50, 70]

print(df.to_dict())
# prints - {'Name': {0: 'John', 1: 'Mark', 2: 'Rick'}, 'Score': {0: 20, 1: 50, 2: 70}}

print(df.to_dict('split'))
# prints - {'index': [0, 1, 2], 'columns': ['Name', 'Score'], 'data': [['John', 20], ['Mark', 50], ['Rick', 70]]}

print(df.to_dict('records'))
# prints - [{'Name': 'John', 'Score': 20}, {'Name': 'Mark', 'Score': 50}, {'Name': 'Rick', 'Score': 70}]

print(df.to_dict('index'))
#prints - {0: {'Name': 'John', 'Score': 20}, 1: {'Name': 'Mark', 'Score': 50}, 2: {'Name': 'Rick', 'Score': 70}}
Was this helpful?