How to Convert Dictionary to Pandas DataFrame (2 Examples)


You can use one of the following methods to convert a dictionary in Python to a pandas DataFrame:

Method 1: Use dict.items()

df = pd.DataFrame(list(some_dict.items()), columns = ['col1', 'col2'])

Method 2: Use from_dict()

df = pd.DataFrame.from_dict(some_dict, orient='index').reset_index()

df.columns = ['col1', 'col2']

Both methods produce the same result.

The following examples show how to use each method in practice.

Example 1: Convert Dictionary to DataFrame Using dict.items()

Suppose we have the following dictionary in Python:

#create dictionary
some_dict = {'Lebron':26,'Luka':30,'Steph':22,'Nicola':29, 'Giannis':31}

We can use the following code to convert this dictionary into a pandas DataFrame:

import pandas as pd

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

#view DataFrame
df

        Player	Points
0	Lebron	26
1	Luka	30
2	Steph	22
3	Nicola	29
4	Giannis	31

We can also use the type() function to confirm that the result is a pandas DataFrame:

#display type of df
type(df)

pandas.core.frame.DataFrame

Example 2: Convert Dictionary to DataFrame Using from_dict()

Suppose we have the following dictionary in Python:

#create dictionary
some_dict = {'Lebron':26,'Luka':30,'Steph':22,'Nicola':29, 'Giannis':31}

We can use the following code to convert this dictionary into a pandas DataFrame:

import pandas as pd

#convert dictionary to pandas DataFrame
df = pd.DataFrame.from_dict(some_dict, orient='index').reset_index()

#define column names of DataFrame
df.columns = ['Player', 'Points']

#view DataFrame
df

        Player	Points
0	Lebron	26
1	Luka	30
2	Steph	22
3	Nicola	29
4	Giannis	31

We can also use the type() function to confirm that the result is a pandas DataFrame:

#display type of df
type(df)

pandas.core.frame.DataFrame

Notice that this method produces the exact same result as the previous method.

Additional Resources

The following tutorials explain how to perform other common tasks in pandas:

How to Convert Pandas DataFrame to Dictionary
How to Convert Pandas Pivot Table to DataFrame
How to Convert Pandas GroupBy Output to DataFrame

Leave a Reply

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