Converting tree list to hierarchy dict

前端 未结 5 1747
日久生厌
日久生厌 2021-02-06 06:39

I have a list of elements with attrs: parent, level, is_leaf_node, is_root_node, is_child_node.

I want to convert this list to hierarchy dict. Example of output dict:

5条回答
  •  不知归路
    2021-02-06 07:33

    Here's a less sophisticated, recursive version like chmod 700 described. Completely untested of course:

    def build_tree(nodes):
        # create empty tree to fill
        tree = {}
    
        # fill in tree starting with roots (those with no parent)
        build_tree_recursive(tree, None, nodes)
    
        return tree
    
    def build_tree_recursive(tree, parent, nodes):
        # find children
        children  = [n for n in nodes if n.parent == parent]
    
        # build a subtree for each child
        for child in children:
            # start new subtree
            tree[child.name] = {}
    
            # call recursively to build a subtree for current node
            build_tree_recursive(tree[child.name], child, nodes)
    

提交回复
热议问题