Convert Pandas DataFrame to a Dictionary

To convert Pandas DataFrame to a dictionary:

my_dictionary = df.to_dict()

Steps to Convert Pandas DataFrame to a Dictionary

Step 1: Create a DataFrame

For example, 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)

print(df)
print(type(df))

You’ll then get the following DataFrame:

   Product  Price
0   Laptop   1200
1  Printer    100
2  Monitor    300
3   Tablet    150
<class 'pandas.core.frame.DataFrame'>

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

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)

my_dictionary = df.to_dict()

print(my_dictionary)
print(type(my_dictionary))

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

{'Product': {0: 'Laptop', 1: 'Printer', 2: 'Monitor', 3: 'Tablet'}, 'Price': {0: 1200, 1: 100, 2: 300, 3: 150}}
<class 'dict'>

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)

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

print(my_dictionary)
print(type(my_dictionary))

You’ll now get the following orientation:

{'Product': ['Laptop', 'Printer', 'Monitor', 'Tablet'], 'Price': [1200, 100, 300, 150]}
<class 'dict'>

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)

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

print(my_dictionary)
print(type(my_dictionary))

You’ll now see the following orientation:

{'index': [0, 1, 2, 3], 'columns': ['Product', 'Price'], 'data': [['Laptop', 1200], ['Printer', 100], ['Monitor', 300], ['Tablet', 150]]}
<class 'dict'>

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

Leave a Comment