Convert a Dictionary to Pandas DataFrame

You may use the following template to convert a dictionary to Pandas DataFrame:

import pandas as pd

my_dict = {'key_1': 'value_1', 'key_2': 'value_2', ...}

df = pd.DataFrame(list(my_dict.items()), columns=['column_1', 'column_2'])

print(df)

Steps to Convert a Dictionary to Pandas DataFrame

Step 1: Gather the Data for the Dictionary

To start, gather the data for your dictionary. For example, let’s gather the following data about products and prices:

ProductPrice
Computer1500
Monitor300
Printer150
Desk250

Step 2: Create the Dictionary

Next, create the dictionary.

For our example, you may use the following code to create the dictionary:

my_dict = {'Computer': 1500, 'Monitor': 300, 'Printer': 150, 'Desk': 250}

print(my_dict)
print(type(my_dict))

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

{'Computer': 1500, 'Monitor': 300, 'Printer': 150, 'Desk': 250}
<class 'dict'>

Notice that the syntax of print(type(my_dict)) was add at the bottom of the code to confirm that we indeed got a dictionary.

Step 3: Convert the Dictionary to a DataFrame

For the final step, convert the dictionary to a DataFrame using this template:

import pandas as pd

my_dict = {'key_1': 'value_1', 'key_2': 'value_2', ...}

df = pd.DataFrame(list(my_dict.items()), columns=['column_1', 'column_2'])

print(df)

For our example, here is the complete Python code to convert the dictionary to a DataFrame:

import pandas as pd

my_dict = {'Computer': 1500, 'Monitor': 300, 'Printer': 150, 'Desk': 250}

df = pd.DataFrame(list(my_dict.items()), columns=['Products', 'Prices'])

print(df)
print(type(df))

As you can see, the dictionary was converted to Pandas DataFrame:

   Products  Prices
0  Computer    1500
1   Monitor     300
2   Printer     150
3      Desk     250
<class 'pandas.core.frame.DataFrame'>

Leave a Comment