Export pandas dataframe to a nested dictionary from multiple columns Its a similar question to

Export pandas to dictionary by combining multiple row values

But in this case I want something different.

from pandas import DataFrame

df = DataFrame([
           ['A', 123, 1], 
           ['B', 345, 5], 
           ['C', 712, 4],
           ['B', 768, 2], 
           ['B', 768, 3], 
           ['A', 123, 9], 
           ['C', 178, 6], 
           ['C', 178, 5],  
           ['A', 321, 3]], 
           columns=['maingroup', 'subgroup', 'selectedCol'])


I'd want the output to be:

{
 'A': {'123':[1, 9], '321':[3]},
 'B': {'345':[5], '768':[2, 3]},
 'C': {'712':[4], '178':[6, 5]}
}
Using dict comprehension with nested groupby:

d = {k: f.groupby('subgroup')['selectedCol'].apply(list).to_dict()
     for k, f in df.groupby('maingroup')}


Output:

{'A': {123: [1, 9], 321: [3]},
 'B': {345: [5], 768: [2, 3]},
 'C': {178: [6, 5], 712: [4]}}