gpt4 book ai didi

python - 以多级树的形式构建字典

转载 作者:太空宇宙 更新时间:2023-11-04 11:06:40 24 4
gpt4 key购买 nike

我从数据库对象中获取,这些对象是数据库中按树排序的目录条目:

db_tree = [
{"id":2, "parent_id":1, "level":1, "name":"parent 1"},
{"id":5, "parent_id":2, "level":2, "name":"child 1 - 1"},
{"id":6, "parent_id":2, "level":2, "name":"child 1 - 2"},
{"id":9, "parent_id":2, "level":2, "name":"child 1- 3"},
{"id":7, "parent_id":5, "level":3, "name":"child 1 - 1 - 1"},
{"id":11, "parent_id":6, "level":3, "name":"children 2- 1"},
{"id":10, "parent_id":7, "level":4, "name":"child 4 levl parent 1"},
{"id":3, "parent_id":1, "level":1, "name":"parent 2"},
{"id":13, "parent_id":3, "level":2, "name":"parent 2- 1 - chil"},
{"id":4, "parent_id":1, "level":1, "name":"parent 3"},
{"id":8, "parent_id":1, "level":1, "name":"parent 4"}
]

列表已经按树排序,即有一个父部分(第 1 层),然后,如果有子部分,则为第 1 层的下一个部分。我需要将这些数据带到这种字典中:

tree = {}
tree['parent 1'] = {}
tree['parent 1']['child 1 - 1'] = {}
tree['parent 1']['child 1 - 1']['child 1 - 1 - 1'] = {}
tree['parent 1']['child 1 - 1']['child 1 - 1 - 1']['child 4 levl parent 1'] = {}
tree['parent 1']['child 1 - 2'] = {}
tree['parent 1']['child 1 - 2']['children 2- 1'] = {}
tree['parent 1']['child 1- 3'] = {}
tree['parent 1']['child1']['child3'] = {}

tree['parent 2'] = {}
tree['parent 2']['parent 2- 1 - chil'] = {}

tree['parent 3'] = {}
tree['parent 4'] = {}

如果有人遇到过或做过这个,请告诉我

最佳答案

为了更好的代码可读性和可视化,您可以利用 networkx 的优势:

import networkx as nx
import pprint
G = nx.DiGraph()
for n in db_tree:
G.add_node(n["name"]) #adds node
children = [x for x in db_tree if x["id"] == n["parent_id"]]
if children:
G.add_edge(n["name"], children[0]["name"]) #add directed edge if it has
nx.draw(G, with_labels=True)

不幸的是,它没有将图转换为嵌套字典数据结构的简单方法。

输出:

enter image description here

关于python - 以多级树的形式构建字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59276241/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com