Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python/物化路径:从平面列表递归创建嵌套dict_Python_Mongodb - Fatal编程技术网

Python/物化路径:从平面列表递归创建嵌套dict

Python/物化路径:从平面列表递归创建嵌套dict,python,mongodb,Python,Mongodb,我试图从mongodb中包含路径字符串的dict平面列表中创建一个嵌套dict结构,以便构建一个将在d3中显示的树。例如,以下是一组数据示例: [ { "_id" : 1, "name" : "var", "path" : "/" }, { "_id" : 2, "name" : "var", "path" : "/var/" }, { "_id" : 3, "name" : "log", "path" : "/var/var/" }, { "_i

我试图从mongodb中包含路径字符串的dict平面列表中创建一个嵌套dict结构,以便构建一个将在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结构

这可能会解决它吗

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)