Create Dictionary from pandas DataFrame in Python (Example Code)

In this post, I’ll demonstrate how to transform a pandas DataFrame to a dictionary in Python.

Setting up the Example

import pandas as pd                    # Import pandas library in Python
my_df = pd.DataFrame({'A': ['xxx'],    # Constructing a pandas DataFrame
                      'B': ['yyy'],
                      'C': ['zzz']})
print(my_df)
#      A    B    C
# 0  xxx  yyy  zzz

Example: Applying to_dict() Function to Convert pandas DataFrame to Dictionary

df_to_dict = my_df.to_dict()           # Using to_dict
print(df_to_dict)
# {'A': {0: 'xxx'}, 'B': {0: 'yyy'}, 'C': {0: 'zzz'}}

Related Articles & Further Resources

You may have a look at the following Python programming language tutorials. They illustrate topics such as data conversion and lists.

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top