-1
index      print_type_solid      print_type_floral  cluster
     A           10                     10            2
     B           20                     20            2
     A           10                     10            3
     B           20                     20            3
     C           25                     30            3

Can someone help me convert the above dataframe into the following nested dictionary where the cluster becomes the main key and and the print_type_x as key and then the values as shown in the expected output below ?

 {  
 "2" :{
        "print_type_solid" : {
          "A": 10,
          "B": 20
                            },
        "print_type_floral" : {
            "A": 10,
            "B": 20
                             }
        },

"3" :{
        "print_type_solid" : {
          "A": 10,
          "B": 20,
          "C": 25,
                            },
        "print_type_floral" : {
            "A": 10,
            "B": 20,
            "C": 30,
                             }
        }

}

1 Answers1

0

Not sure why you would want to create a nested dictionaries from pandas dataframe as there are many better ways to iterate over and find required values from dataframes but a simple script would look something like this where df is the dataframe you have mentioned.

df = 
    index      print_type_solid print_type_floral   cluster             
        A                10                10              2
        B                20                20              2
        A                10                10              3
        B                20                20              3

d = {}
for i in set(df['cluster']):
    d2 = {}
    df_1 = df[df['cluster']==i]
    for j in [*df][:-1]:
        d3 = {}
        for k in df_1.index:
            d3[k] = df_1[j][k]
        d2[j] = d3
    d[i] = d2

output will be as such

d = {
    2: {
        'print_type_solid': {
            'A': 10, 
            'B': 20
        },
        'print_type_floral': {
            'A': 10, 
            'B': 20}
    },
     3: {
         'print_type_solid': {
             'A': 10, 
             'B': 20
         },
  'print_type_floral': {
      'A': 10, 
      'B': 20
        }
    }
}