且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从给定的字典创建一棵树

更新时间:2022-02-14 18:43:59

您可以使用 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 时才添加节点.当父为 None 时,将其添加为 root.

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.