This tutorial will discuss about unique ways to create a dictionary from a dataframe in Python.
Suppose we have a DataFrame,
Name Age City 0 John 30 Tokyo 1 Ritika 35 London 2 Atharv 25 Paris
Nowm we want to create a list of dictionaries from this DataFrame. Like this,
[{'Name': 'John', 'Age': 30, 'City': 'Tokyo'}, {'Name': 'Ritika', 'Age': 35, 'City': 'London'}, {'Name': 'Atharv', 'Age': 25, 'City': 'Paris'}]
In the DataFrame, we have 3 columns i,e. Name, Age and City. There are 3 rows in the DataFrame. We want each row as a separate dictionary, where keys will be the column names and values will be the a row.
So we can do that using the to_dict() method of the DataFrame. In this method, we need to pass the orientation as records, and it will return a list of dictionary.
In this returned list each dictionares, each dictionary represent a single row from the DataFrame. In each dictionary the keys are the column names and values are the row values.
Let’s see the complete example,
Frequently Asked:
import pandas as pd # Create a DataFrame df = pd.DataFrame({'Name' : ['John', 'Ritika', 'Atharv'], 'Age' : [30, 35, 25], 'City' : ['Tokyo', 'London', 'Paris']}) # print the DataFrame print(df) # Convert the DataFrame to a Dictionary dictObj = df.to_dict(orient='records') print(dictObj)
Output
Name Age City 0 John 30 Tokyo 1 Ritika 35 London 2 Atharv 25 Paris [{'Name': 'John', 'Age': 30, 'City': 'Tokyo'}, {'Name': 'Ritika', 'Age': 35, 'City': 'London'}, {'Name': 'Atharv', 'Age': 25, 'City': 'Paris'}]
Summary
We learned how to create a Dictionary from a DataFrame.