convert dataframe to nested dictionary python code example

Example: python How to convert a dictionary of dictionaries nested dictionary to a Pandas dataframe

# Basic syntax:
dataframe = pd.DataFrame(nested_dictionary)
dataframe = dataframe.transpose()

# Note, this only works if your nested dictionaries are set up in a 
# 	specific way. See below. 

# Create nested dictionary:
import pandas as pd
student_data = { 
0 : {
    'name' : 'Aadi',
    'age' : 16,
    'city' : 'New york'
    },
1 : {
    'name' : 'Jack',
    'age' : 34,
    'city' : 'Sydney'
    },
2 : {
    'name' : 'Riti',
    'age' : 30,
    'city' : 'Delhi'
    }
}

# Example usage:
pandas_dataframe = pd.DataFrame(student_data) 
print(pandas_dataframe)
             0       1      2 # Outer keys become column names
age         16      34     30
city  New york  Sydney  Delhi
name      Aadi    Jack   Riti

pandas_dataframe.transpose()
  age      city  name # After transposing, inner keys become column names
0  16  New york  Aadi
1  34    Sydney  Jack
2  30     Delhi  Riti