Convert flat list of dicts to hierarchy tree
08:32 06 Feb 2019

I've been having trouble trying to convert the following list:

lst = [
    {"id": 0, "job": "CEO", "ManagerID": 0, "name": "John Smith"},
    {"id": 1, "job": "Medical Manager", "ManagerID": 0, "name": "Medic 1"},
    {"id": 2, "job": "Medical Assist", "ManagerID": 1, "name": "Medic 2"},
    {"id": 3, "job": "ICT Manager", "ManagerID": 0, "name": "ICT 1"},
    {"id": 4, "job": "ICT Assist", "ManagerID": 3, "name": "ICT 2"},
    {"id": 5, "job": "ICT Junior", "ManagerID": 4, "name": "ICT 3"}
]

Into the format like

output = [
    {"id": 0, "job": "CEO", "ManagerID": 0, "name": "John Smith", "children" : [
        { "id":1, "job": "Medical Manager", "name": "Medic 1", "children" : [
            {"id": 2, "job": "Medical Assist", "name": "Medic 2"}
            ]
        },
        {"id": 3, "job": "ICT Manager", "name": "ICT 1", "children":[
            {"id": 4, "job": "ICT Assist", "name": "ICT 2", "children" : [
                {"id": 5, "job": "ICT Junior", "name": "ICT 3"}
            ]}
        ]}
    ],
}]

Where there is one root node (ManagerID = 0) any everything else branches off.

I've tried to adapt code from another question but I was unable produce this required format

The code i've been using is as follows, but this still has repeats of parent nodes

classes = [] #everyones id
for item in lst:
    name = item['id']
    if name not in classes:
        classes.append(name)

treenodes = {}
root_node = None

for item in lst: # Create  tree nodes
    item['children'] = []
    name = item['id']
    treenodes[name] = item
    parent = item['ManagerID']
    if parent not in classes: # parent is root node, create
        if parent not in treenodes:
            node = {}
            node['ManagerID'] = 0 #set manager to root
            node['children'] = []
            node['id'] = parent
            root_node = node
            treenodes[parent] = node

# Connect parents and children
for item in lst: # Create  tree nodes
    parent = item['ManagerID']
    parent_node = treenodes[parent]
    parent_node['children'].append(item)

output = treenodes
python list dictionary tree hierarchy