
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python Pandas - Convert Nested Dictionary to Multiindex Dataframe
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
- Related Articles
- Python - Convert list of nested dictionary into Pandas Dataframe
- Python Pandas - Create Multiindex from dataframe
- Python - Drop specific rows from multiindex Pandas Dataframe
- Python Convert nested dictionary into flattened dictionary?
- Python - Convert flattened dictionary into nested dictionary
- How to convert a DataFrame into a dictionary in Pandas?
- Python - Convert Pandas DataFrame to binary data
- Convert Nested Tuple to Custom Key Dictionary in Python
- Python Pandas - How to Sort MultiIndex
- Python Pandas - Create a DataFrame with the levels of the MultiIndex as columns
- How to convert pandas DataFrame into JSON in Python?
- Python - Convert one datatype to another in a Pandas DataFrame
- How to create nested Python dictionary?
- Python - How to rename multiple column headers in a Pandas DataFrame with Dictionary?
- Python Pandas - Convert a MultiIndex to an Index of Tuples containing the level values

Advertisements