Open In App

How to convert Dictionary to Pandas Dataframe?

Last Updated : 03 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

A dictionary, with its key-value structure, can easily be transformed into a DataFrame, a tabular format. Default Pandas DataFrame constructor is the most versatile and straightforward method to convert a dictionary into a DataFrame.

Method 1: Using Pandas Constructor

By passing the dictionary directly to this constructor, each key in the dictionary becomes a column label, while the values form the data within those columns. In this example, we are using Pandas constructor – pd.DataFrame().

Python
import pandas as pd

data = {'name': ['nick', 'david', 'joe', 'ross'],'age': ['5', '10', '7', '6']}
data = pd.DataFrame.from_dict(data)
print(data)

Output
    name age
0   nick   5
1  david  10
2    joe   7
3   ross   6

Method 2. Converting Dictionary to DataFrame With DataFrame.from_dict()

The pd.DataFrame.from_dict() method offers additional flexibility when converting dictionaries to DataFrames i.e to specify the orientation of the DataFrame using the orient parameter. Provides control over how your data is structured. In this example:

  • We are using list of dictionary to convert the dictionary into a Pandas Dataframe.
  • We are using the orient parameter to change the orientation of the dataframe from column to index
Python
import pandas as pd
data = {'area': ['new-hills', 'cape-town', 'mumbai'],'rainfall': [100, 70, 200],'temperature': [20, 25, 39]}

df = pd.DataFrame.from_dict(data, orient='index')
print(df)

Output
                     0          1       2
area         new-hills  cape-town  mumbai
rainfall           100         70     200
temperature         20         25      39

Handling Dictionaries with Unequal Lengths

When dictionaries have lists of values with different lengths, converting them directly might result in errors. In such cases, you can first convert each key-value pair into separate Series and then combine them into a DataFrame

Python
import pandas as pd
# keys and list of values with different lengths to Pandas Dataframe.
data = {'key1': [1, 2, 3],'key2': [4, 5],'key3': [6, 7, 8, 9]}
df = pd.DataFrame(list(data.items()), columns=['Key', 'Values'])

print(df)

Output
    Key        Values
0  key1     [1, 2, 3]
1  key2        [4, 5]
2  key3  [6, 7, 8, 9]


Next Article
Practice Tags :

Similar Reads