Skip to content Skip to sidebar Skip to footer

Transforming A List Of Nodes In To A Nested Dict In Python

I have a list of dicts in python that represents an adjacency list and i want to transform this list in to a nested python dict. with name and children keys. List of nodes This is

Solution 1:

You can use the function with slight modifications:

  • Use the 'children' key instead of 'sub'
  • Initialise the root node with only the keys you want to have (name & children)
  • Instead of calling .update (which copies all keys), assign just the 'name' key
def list_to_tree(data):
    out = { 
        0: { 'name': 'rootnode', 'children': [] }
    }

    for p in data:
        out.setdefault(p['parent_id'], { 'children': [] })
        out.setdefault(p['id'], { 'children': [] })
        out[p['id']]['name'] = p['name']
        out[p['parent_id']]['children'].append(out[p['id']])

    return out[0]

Post a Comment for "Transforming A List Of Nodes In To A Nested Dict In Python"