How to Convert Pandas DataFrame to a Dictionary

The following syntax can be used to convert Pandas DataFrame to a dictionary:

my_dictionary = df.to_dict()

Next, you’ll see the complete steps to convert a DataFrame to a dictionary. You’ll also learn how to apply different orientations for your dictionary.

Steps to Convert Pandas DataFrame to a Dictionary

Step 1: Create a DataFrame

To begin with a simple example, let’s create a DataFrame with two columns:

import pandas as pd

data = {'Product': ['Laptop','Printer','Monitor','Tablet'],
        'Price': [1200,100,300,150]
        }
df = pd.DataFrame(data, columns = ['Product', 'Price'])

print (df)
print(type(df))

You’ll then get the following DataFrame:

Example of data

Note that the syntax of print(type(df)) was added at the bottom of the code to demonstrate that we got a DataFrame (as highlighted in red).

Step 2: Convert the DataFrame to a Dictionary

You can use df.to_dict() in order to convert the DataFrame to a dictionary.

Here is the complete code to perform the conversion:

import pandas as pd

data = {'Product': ['Laptop','Printer','Monitor','Tablet'],
        'Price': [1200,100,300,150]
        }
df = pd.DataFrame(data, columns = ['Product', 'Price'])

my_dictionary = df.to_dict()

print (my_dictionary)
print(type(my_dictionary))

Run the code, and you’ll get this dictionary:

How to Convert Pandas DataFrame to a Dictionary

The above dictionary has the following ‘dict‘ orientation (which is the default):

{'column name':{index value:'column value'}}

You may pick other orientations based on your needs. Let’s now review two additional orientations:

  • The ‘list‘ orientation
  • The ‘split‘ orientation

The List Orientation

The ‘list’ orientation has the following structure:

{'column name':['column values']}

In order to get the list orientation, you’ll need to set orient = ‘list’ as captured below:

import pandas as pd

data = {'Product': ['Laptop','Printer','Monitor','Tablet'],
        'Price': [1200,100,300,150]
        }
df = pd.DataFrame(data, columns = ['Product', 'Price'])

my_dictionary = df.to_dict(orient = 'list')

print (my_dictionary)
print(type(my_dictionary))

You’ll now get the following orientation:

Convert Pandas DataFrame to a Dictionary

The Split Orientation

The ‘split’ orientation looks like this:

{'index':[index values],'columns':['column names'], 'data': [[column values]]}

To get the split orientation, set orient = ‘split’ as follows:

import pandas as pd

data = {'Product': ['Laptop','Printer','Monitor','Tablet'],
        'Price': [1200,100,300,150]
        }
df = pd.DataFrame(data, columns = ['Product', 'Price'])

my_dictionary = df.to_dict(orient = 'split')

print (my_dictionary)
print(type(my_dictionary))

You’ll now see the following orientation:

Pandas DataFrame to Dictionary

There are additional orientations to choose from. You can check the Pandas Documentations for the complete list of orientations that you may apply.