TransWikia.com

Convert heirachy to dict of lists

Stack Overflow Asked by himabindu on November 18, 2021

I want to convert a hierarchy to a dictionary of lists.
I am just sharing the sample hierarchy. We need to write the recursive function for this but I am not able to get the idea how to write it

Input:
[('A', 'B'),
 ('A', 'C'),
 ('A', 'D', 'E'),
 ('A', 'D', 'F'),
 ('A', 'D', 'G'),
 ('A', 'D', 'G', 'H'),
 ('A', 'F')
]

I want output like

{'_id': 'A',
 'children':[
    {'_id':'B'},
    {'_id', 'C'},
    {'_id', 'D', 
     'children':[
       {'_id':'E'}, 
       {'_id':'F'}, 
       {'_id':'G', 
        'children':[
          {'_id':'H'}
        ]
       }
      ]
    }
    {'_id':'F'}
 ]
}

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP