我试图从包含路径字符串的平面列表中创建一个嵌套的dict结构,来自mongodb,以便构建一个将在d3中显示的树。例如,这是一组示例数据:
[ { "_id" : 1, "name" : "var", "path" : "/" }, { "_id" : 2, "name" : "var", "path" : "/var/" }, { "_id" : 3, "name" : "log", "path" : "/var/var/" }, { "_id" : 4, "name" : "log2", "path" : "/var/var/" }, { "_id" : 5, "name" : "uwsgi", "path" : "/var/var/log/" }, { "_id" : 6, "name" : "nginx", "path" : "/var/var/log2/" }, { "_id" : 7, "name" : "error", "path" : "/var/var/log2/nginx/" }, { "_id" : 8, "name" : "access", "path" : "/var/var/log2/nginx/" } ]
我需要将数据转换为这种格式的节点,其中包含name属性和子节点列表以显示图表
{ 'name': 'var', '_id': 1, 'children': [ { 'name': 'var' '_id': 2 'children': [ { '_id': 3 'name': 'log', 'children': [ { '_id':5, 'name': 'uwsgi', 'children': [] } ] }, { '_id': 4 'name': 'log2', 'children': [ { '_id': 6, 'name': 'nginx', 'children': [ { '_id': 7, 'name': 'error', 'children': [] }, { '_id': 8, 'name', 'access', 'children': [] } ] } ] } ] } ] }
我尝试了类似这样的功能:
def insert_node(d, res): if not res.get("children"): res["children"] = [] if d["path"] == res["path"]: res["children"].append(d) else: for c in res["children"]: insert_node(d, c) root = nodes[0] for node in nodes[1:] insert_node(node, root)
是否有一种优雅的递归方式来填充嵌套的dict结构?
答案 0 :(得分:0)
这可能会解决它吗?
def insert_node(d, res):
if not res.get("children"):
res["children"] = []
if d["path"] == res["path"]+res['name']+'/':
res["children"].append(d)
else:
for c in res["children"]:
insert_node(d, c)
root = nodes[0]
for node in nodes[1:]
insert_node(node, root)