Convert pandas pivot table with multiindex into nested dictionary


Keywords:python 


Question: 

I looked through the various answers similar to my question, but could not find a solution for my specific case.

I am creating a pandas pivot table with a multiindex as such:

df = pd.pivot_table(df, index  = ['clusterKey',
                                 'campaignTitle',
                                 'couponName'],
                        values = ['salesValue','budgetSpent'])

and I'd like to create a data structure where the indexes are converted into a nested dictionary, so it becomes possible to access the datastructure like this:

val = dict['clusterKeyA']['campaignTitleB']['couponNameC']['salesValue']

1 Answer: 

Not sure if you are ok with this format but you can directly use pd.DataFrame.to_dict(), which is very easy and short. Then, you can access value using double nested dictionary, where the first level is a tuple of your three indices.

d = pt.to_dict("index")
d
{('A', 'a', 'd'): {'val1': 1.5, 'val2': 1.0},
 ('A', 'b', 'a'): {'val1': 3.0, 'val2': 4.0},
 ('B', 'a', 'a'): {'val1': 4.0, 'val2': 4.0},
 ('B', 'b', 'c'): {'val1': 5.0, 'val2': 1.0},
 ('B', 'c', 'c'): {'val1': 6.0, 'val2': 1.0},
 ('C', 'b', 'a'): {'val1': 7.0, 'val2': 3.0},
 ('C', 'b', 'b'): {'val1': 8.0, 'val2': 3.0},
 ('C', 'c', 'c'): {'val1': 9.0, 'val2': 1.0},
 ('C', 'c', 'd'): {'val1': 1.0, 'val2': 1.0}}

d[("A","a","d")]["val1"]
1.5