Pandas - Convert DataFrame to List of Dictionaries


Pandas - Convert DataFrame to List of Dictionaries

In Pandas, to convert a DataFrame to a list of dictionaries, you can use to_dict() method of DataFrame instance.

Call to_dict() method on the given DataFrame, and pass the value of 'records' for the orient parameter.

For example, the syntax to convert a DataFrame df to a list of objects using to_dict() method is

df.to_dict(orient='records')

In the returned list of dictionaries, each dictionary is constructed from the respective row in DataFrame. The keys in dictionary are the column labels in the DataFrame, and the respective values in dictionary are the row values in DataFrame.

In this tutorial, we will go through some examples, with step by step explanation of how to convert a given DataFrame to a list of dictionaries.

Examples

1. Convert given DataFrame to list of dictionaries using to_dict()

In this example, we are given a DataFrame in df. We have to convert this DataFrame to a list of dictionaries using DataFrame.to_dict() method.

Steps

  1. Given a DataFrame in df with three columns 'A', 'B', and 'C', and four rows.
df = pd.DataFrame({
    'A': [2, 4, 6, 8],
    'B': [1, 3, 5, 7],
    'C': [10, 20, 30, 40]})
  1. Call to_dict() method on the DataFrame df, and store the returned list of dictionaries in list_of_dicts.
list_of_dicts = df.to_dict(orient='records')
  1. You may print the list of dictionaries in list_of_dicts to output using print() function.
print(list_of_dicts)

Program

The complete program to convert a given DataFrame to a list of dictionaries.

Python Program

import pandas as pd


# Take a DataFrame
df = pd.DataFrame({
    'A': [2, 4, 6, 8],
    'B': [1, 3, 5, 7],
    'C': [10, 20, 30, 40]})

# Convert dataframe to list of dictionaries
list_of_dicts = df.to_dict(orient='records')

# Print the list of dictionaries
print(list_of_dicts)

Output

[
  {'A': 2, 'B': 1, 'C': 10},
  {'A': 4, 'B': 3, 'C': 20},
  {'A': 6, 'B': 5, 'C': 30},
  {'A': 8, 'B': 7, 'C': 40}
]

The row [2 1 10] has been converted to a dictionary with the column labels as keys, and the row values as the respective values for keys. Similarly, for the rest of rows in DataFrame. Hence, there are as many dictionaries inside the list, as there are rows in the DataFrame.

Summary

In this Pandas Tutorial, we learned how to convert a given DataFrame to a list of dictionaries using to_dict() method, with examples.