Python - Create pandas dataframe from dictionary of dictionaries

Given dictionary of dictionaries, we have to create pandas dataframe from it. By Pranit Sharma Last updated : September 26, 2023

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Python dictionaries are used to store heterogeneous data. The data is stored in key:value pair. A dictionary is a mutable collection and ordered in nature and does not allow duplicates which mean there are unique keys in a dictionary.

A dictionary key can have any type of data as its value, for example, a list, tuple, string, or a dictionary itself.

If a key's value is a dictionary, it is called a nested dictionary. Suppose multiple keys have dictionaries as their values and we have to create a pandas DataFrame from this nested dictionary, pandas will help us to achieve this task.

Problem statement

Given dictionary of dictionaries, we have to create pandas dataframe from it.

Creating pandas dataframe from dictionary of dictionaries

To create pandas DataFrame from the dictionary of dictionaries, we will use the pd.DataFrame.from_dict() method. If we have a very huge nested dictionary, this method allows us to extract keys inside keys and fetch their values to create columns and rows of the DataFrame.

Let us understand with the help of an example,

Python program to create pandas dataframe from dictionary of dictionaries

# Importing pandas package
import pandas as pd

# Creating a nested dictionary
d = {'Gwalior':
         {'Phone':
              {'Stock':
                   40000,
               'Sale':
                   3700},
                'Fridge':
                    {'Stock':
                         28000,
                     'Sale':
                         19000}
          },
     'Varanasi':
         {'Phone':
              {'Stock':
                   80000,
               'Sale':
                   47000},
     'Fridge':
         {'Stock':
              22000,
          'Sale':
              13000}
          }
     }

# Creating a DataFrame
df = pd.DataFrame.from_dict({(i,j): d[i][j] for i in d.keys() for j in d[i].keys()},orient='index')

# Display DataFrame
print("Created DataFrame:\n",df)

Output

The output of the above program is:

Example: Create pandas dataframe from dictionary of dictionaries

Python Pandas Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.