[Answer]-How to build a recursive dictionary tree from an ordered adjacency list

1👍

Maybe there are better ways, but here is one solution:

users = [
    {
        'id': 232,
        'name': 'jon',
        'parent': None
    },
    {
        'id': 3522,
        'name': 'dave',
        'parent': 232
    },
    {
        'id': 2277,
        'name': 'alice',
        'parent': 3522
    },
    {
        'id': 119,
        'name': 'gary',
        'parent': 232
    },
    {
        'id': 888,
        'name': 'gunthe',
        'parent': 119
    },
    {
        'id': 750,
        'name': 'beavis',
        'parent': None
    },
    {
        'id': 555,
        'name': 'urte',
        'parent': 750
    }
]

users_map = {}
for user in users:
    users_map[user['id']] = user

users_tree = []
for user in users:
    if user['parent'] is None:
        users_tree.append(user)
    else:
        parent = users_map[user['parent']]
        if 'childs' not in parent:
            parent['childs'] = []
        parent['childs'].append(user)

print(users_tree)

#user as {data: user, childs: []}

users_map = {}
for user in users:
    users_map[user['id']] = {'data': user, 'childs': []}

users_tree = []
for user in users:
    if user['parent'] is None:
        users_tree.append(users_map[user['id']])
    else:
        parent = users_map[user['parent']]
        parent['childs'].append(users_map[user['id']])

print(users_tree)
👤Todor

Leave a comment