Python/物化路径:从扁平列表递归创建嵌套字典

1 投票
1 回答
627 浏览
提问于 2025-04-30 15:58

我正在尝试从一个平坦的字典列表中创建一个嵌套的字典结构,这些字典里包含了路径字符串,数据来自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': '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)

有没有一种优雅的递归方法来填充这个嵌套的字典结构?

暂无标签

1 个回答

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)

撰写回答