从给定的字典创建树 [英] Create a tree from a given dictionary

查看:114
本文介绍了从给定的字典创建树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个python字典,我想从中创建一棵树。
字典是这样的:

I have a python dictionary and I would like to create a tree from it. The dictionary is something like this:

dict_={"2":{'parent': "1"},"1":{'parent': None},"3":{'parent': "2"}}

在这种情况下,根是 1

in this case, the root is "1"

我尝试使用treelib库,但是当我在字典上迭代并创建一个节点,其父级尚未创建。例如,如果我要为 2创建一个节点,则尚未创建其父级( 1),因此不能这样做。任何的想法?

I tried to use treelib library but the problem when I iterate on the dictionary and create a node, its parent isn't created yet. For example, if I want to create a node for "2", its parent("1") isn't created yet, so can not do it. Any idea?

推荐答案

您可以使用treelib执行以下操作:

You could do the following, using treelib:

from treelib import Node, Tree

dict_ = {"2": {'parent': "1"}, "1": {'parent': None}, "3": {'parent': "2"}}

added = set()
tree = Tree()
while dict_:

    for key, value in dict_.items():
        if value['parent'] in added:
            tree.create_node(key, key, parent=value['parent'])
            added.add(key)
            dict_.pop(key)
            break
        elif value['parent'] is None:
            tree.create_node(key, key)
            added.add(key)
            dict_.pop(key)
            break

tree.show()

输出

1
└── 2
    └── 3

这个想法是添加一个仅当父级存在于树中或父级为 None 时,才可以选择节点。当父对象时,将其添加为根。

The idea is to add a node only if the parent is present in the tree or the parent is None. When the parent is None add it as root.

这篇关于从给定的字典创建树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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