Python Pandas - Convert Nested Dictionary to Multiindex Dataframe

PythonServer Side ProgrammingProgramming

At first, let us create a Nested Dictionary −

dictNested = {'Cricket': {'Boards': ['BCCI', 'CA', 'ECB'],'Country': ['India', 'Australia', 'England']},'Football': {'Boards': ['TFA', 'TCSA', 'GFA'],'Country': ['England', 'Canada', 'Germany']
   }}

Now, create an Empty Dictionary −

new_dict = {}

Now, loop to assign values −

for outerKey, innerDict in dictNested.items():
   for innerKey, values in innerDict.items():
      new_dict[(outerKey, innerKey)] = values

Convert to Multi-index DataFrame −

pd.DataFrame(new_dict)

Example

Following is the code −

import pandas as pd

# Create Nested dictionary
dictNested = {'Cricket': {'Boards': ['BCCI', 'CA', 'ECB'],'Country': ['India', 'Australia', 'England']},'Football': {'Boards': ['TFA', 'TCSA', 'GFA'],'Country': ['England', 'Canada', 'Germany']
   }}

print"\nNested Dictionary...\n",dictNested

new_dict = {}
for outerKey, innerDict in dictNested.items():
   for innerKey, values in innerDict.items():
      new_dict[(outerKey, innerKey)] = values

# converting to multiindex dataframe
print"\nMulti-index DataFrame...\n",pd.DataFrame(new_dict)

Output

This will produce the following output −

Nested Dictionary...
{'Cricket': {'Country': ['India', 'Australia', 'England'], 'Boards': ['BCCI', 'CA', 'ECB']}, 'Football': {'Country': ['England', 'Canada', 'Germany'], 'Boards': ['TFA', 'TCSA', 'GFA']}}

Multi-index DataFrame...
   Cricket             Football
   Boards   Country   Boards Country
0    BCCI     India      TFA England
1      CA Australia     TCSA  Canada
2     ECB   England      GFA Germany
raja
Published on 16-Sep-2021 08:28:31
Advertisements