Converting tree list to hierarchy dict

前端 未结 5 1865
日久生厌
日久生厌 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:12

    It sounds like what you're basically wanting to do is a variant of topological sorting. The most common algorithm for this is the source removal algorithm. The pseudocode would look something like this:

    import copy
    def TopSort(elems): #elems is an unsorted list of elements.
        unsorted = set(elems)
        output_dict = {}
        for item in elems:
            if item.is_root():
                output_dict[item.name] = {}
                unsorted.remove(item)
                FindChildren(unsorted, item.name, output_dict[item.name])
        return output_dict
    
    def FindChildren(unsorted, name, curr_dict):
        for item in unsorted:
            if item.parent == name:
                curr_dict[item.name] = {}
                #NOTE:  the next line won't work in Python.  You
                #can't modify a set while iterating over it.
                unsorted.remove(item)
                FindChildren(unsorted, item.name, curr_dict[item.name])
    

    This obviously is broken in a couple of places (at least as actual Python code). However, hopefully that will give you an idea of how the algorithm will work. Note that this will fail horribly if there's a cycle in the items you have (say item a has item b as a parent while item b has item a as a parent). But then that would probably be impossible to represent in the format you're wanting to do anyway.

提交回复
热议问题