将树列表转换为层次结构字典 [英] Converting tree list to hierarchy dict

查看:49
本文介绍了将树列表转换为层次结构字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有属性的元素列表:parent、level、is_leaf_node、is_root_node、is_child_node.

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?

推荐答案

这里有一个不太复杂的递归版本,如 chmod 700 所述.当然完全未经测试:

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)

这篇关于将树列表转换为层次结构字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆