Home > Software design >  Group and Nested Group for python
Group and Nested Group for python

Time:10-20

I have some data like this,

menu_list = [
   {'name':'ABC','parent_id':None,'id':5},
   {'name':'XYZ','parent_id':5,'id':7},
   {'name':'APPLE','parent_id':7,'id':8},
   {'name':'Mango','parent_id':5,'id':9},
   {'name':'Mango-small','parent_id':9,'id':10},
]

i was expecting the final group by result like,

ABC
----XYZ
-------- APPLE
----Mango
     ----Mango SMALL

The final output as a dictionary.

I have used collection module of Python, and defaultdict() method. but this do the task only for first level group. But i need the nested and outer both as well. If any suggestion that would be great help. Thanks.

CodePudding user response:

you can use recursive function to solve this problem.

menu_list = [

   {'name':'ABC','parent_id':None,'id':5},
   {'name':'XYZ','parent_id':5,'id':7},
   {'name':'APPLE','parent_id':7,'id':8},
   {'name':'Mango','parent_id':5,'id':9},
   {'name':'Mango-small','parent_id':9,'id':10},
]


def rec_somehing(d:dict,par_id:int,depth:int)->str:
    for i in d:
        if i['parent_id'] == par_id:
            print('....'*depth,i['name'])   
            rec_somehing(d,i['id'],depth 1)

rec_somehing(menu_list,None,1)

#output:
# .... ABC
# ........ XYZ
# ............ APPLE
# ........ Mango
# ............ Mango-small

CodePudding user response:

Instead of fiddling with IDs, you could just organize your data the way you want it. Example:

menu_list = [
   {'name': 'ABC', 'children': [
       {'name': 'XYZ', 'children': [
           {'name': 'APPLE', 'children': []}
       ]},
       {'name': 'Mango', 'children': [
           {'name': 'Mango-small', 'children': []}
       ]}
   ]}
]
  • Related