Search code examples
pythonjsondictionaryrecursiongrouping

Counting the keys in a nested dictionary and create a list containing the count under each keys


I've the following dictionary

{
"Africa":{
   "All":{"ABC":0,"DEF":0,"GHI":0},
   "NA":{"GHI":0},
   "EXPORT":{"ABC":0,"DEF":0,"GHI":0},
   "RE-EXPORT":{"ABC":0,"DEF":0,"GHI":0}
},
"Asia":{
   "All":{"ABC":0,"DEF":0,"GHI":0},
   "NA":{"ABC":0,"DEF":0},
   "RE-EXPORT":{"ABC":0,"GHI":0}
},
"Australia":{
   "All":{"DEF":0,"GHI":0},
   "NA":{"ABC":0,"DEF":0,"GHI":0}
}

}

I have the following list

x=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22]

I need to group the list x as following, based on the nested keys count

    result =  [
    [
        [1,2,3],
        [4],
        [5,6,7],
        [8,9,10]
    ],
    [
        [11,12,13],
        [14,15],
        [16,17]
    ],
    [
        [18,19],
        [20,21,22]
    ]
 ]

I've 3 parent keys(Africa,Asia,Australia) so the result will have 3 lists inside a main list Inside Africa 4 keys, so [[[],[],[],[]] and next under All I've 3 keys, so [[[[1],[2],[3]],[],[],[]] It's basically grouping the values based on nested dictionary keys

I tried with recursion but couldn't achieve this


Solution

  • you can use:

    start=0
    v1=[]
    v2=[]
    for i in a: #  a= dictionary
        for j in list(a[i].keys()):
            mask=list(a[i][j].keys())
            leng=len(mask)
            mask[0:leng]=x[start:start+ leng]
            start+=leng
            v1.append(mask)
        v2.append(v1)
        v1=[]
    
    print(v2)
    '''
    [
        [[1, 2, 3], [4], [5, 6, 7], [8, 9, 10]],
        [[11, 12, 13], [14, 15], [16, 17]],
        [[18, 19], [20, 21, 22]],
    ]
    
    '''