Create nested dictionary from mulitple dataframe columns and Groupby

Original Dataframe example:

ColA     ColB     ColC
Dog      Red       8
Dog      Black     10
Dog      White     2
Dog      Blue      4
Cat      Red       7
Cat      Black     11
Cat      White     12
Cat      Blue      40

Desired dictionary

d =   {'Dog':{'Red': 8, 'Black':10, 'White':2,'Blue':4}, 
       'Cat':{'Red': 7, 'Black':11, 'White':12,'Blue':40}}

Any suggestions is appreciated!

>Solution :

There might be more panda-esque ways, but this works:

result = {animal:dict(zip(subdf.ColB, subdf.ColC)) for animal, subdf in df.groupby('ColA')}

Leave a Reply