2014-10-30 73 views
1

我想創建一個嵌套的字典結構從一個平坦的列表中包含一個路徑字符串,從mongodb,以建立一個樹,將被顯示在d3。舉例來說,這裏是一組數據的一個例子:Python /物化路徑:遞歸創建嵌套字典從平板列表

 

    [ 
     { "_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) 

是否有填充嵌套的字典結構的優雅遞歸的方式?

回答

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)