How to Convert a Dictionary to a DataFrame in Pandas


Occasionally you may be interested in converting a dictionary to a pandas DataFrame. Fortunately this is easy to do using a single line of code in pandas.

This tutorial demonstrates how to convert a dictionary to a pandas DataFrame in practice.

Example: Converting a Dictionary to a DataFrame

Suppose we have the following dictionary that contains the names of five basketball players and their average points scored per game:

import pandas as pd

#define dictionary
d = {'Michael':36,
     'Lebron': 32,
     'Scotty': 28,
     'Larry': 23,
     'Kareem': 22}

The following code shows how to convert this dictionary to a pandas DataFrame with two columns:

#convert dictionary to DataFrame
df = pd.DataFrame(list(d.items()), columns = ['Player','Points'])

#view DataFrame
df


        Player 	 Points
0	Michael	 36
1	Lebron	 32
2	Scotty	 28
3	Larry	 23
4	Kareem	 22

You can verify that your result is a DataFrame by typing:

#view data type
type(df)

pandas.core.frame.DataFrame

This tells us that the dictionary was indeed converted to a pandas DataFrame.

Bonus: Creating Column Names from Dictionary Keys

If you happen to want the dictionary keys to be the column names of the new DataFrame and the dictionary values to be the row values, you can use the following syntax:

import pandas as pd

#define dictionary
d = {'Michael':36,
     'Lebron': 32,
     'Scotty': 28,
     'Larry': 23,
     'Kareem': 22}

#convert dictionary to DataFrame
df = pd.DataFrame([d])

#view DataFrame
df


        Kareem	Larry	Lebron	Michael	Scotty
0	22	23	32	36	28

We can also verify that this result is a DataFrame:

#view data type
type(df)

pandas.core.frame.DataFrame

You can find more Python tutorials here.

Leave a Reply

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