Search code examples
pythontreehierarchical-trees

Converting tree list to hierarchy dict


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:

{
        'Technology':
            {
             'Gadgets':{},
             'Gaming':{},
             'Programming':
                {
                    'Python':{},
                    'PHP':{},
                    'Ruby':{},
                    'C++':{}
                },
             'Enterprise':{},
             'Mac':{},
             'Mobile':{},
             'Seo':{},
             'Ui':{},
             'Virtual Worlds':{},
             'Windows':{},
            },
        'News':{
            'Blogging':{},
            'Economics':{},
            'Journalism':{},
            'Politics':{},
            'News':{}
            },}

I don't know algorithm. How to do it?


Solution

  • 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)