【问题标题】:Python/ materialized paths: recursively create nested dict from flat listPython/物化路径:从平面列表递归创建嵌套字典
【发布时间】:2014-10-30 15:54:07
【问题描述】:

我正在尝试从 mongodb 的包含路径字符串的 dicts 的平面列表创建一个嵌套的 dict 结构,以便构建一个将在 d3 中显示的树。例如,这是一组数据示例:

[ {“_id”:1,“名称”:“var”,“路径”:“/”}, {“_id”:2,“名称”:“var”,“路径”:“/var/”}, {“_id”:3,“名称”:“日志”,“路径”:“/var/var/”}, {“_id”:4,“名称”:“log2”,“路径”:“/var/var/”}, {“_id”:5,“名称”:“uwsgi”,“路径”:“/var/var/log/”}, {“_id”:6,“名称”:“nginx”,“路径”:“/var/var/log2/”}, {“_id”:7,“名称”:“错误”,“路径”:“/var/var/log2/nginx/”}, {“_id”:8,“名称”:“访问”,“路径”:“/var/var/log2/nginx/”} ]

我需要将数据转换为具有名称属性和子节点列表的这种格式的节点才能显示图表

{ “名称”:“变量”, '_id': 1, '孩子们': [ { “名称”:“变量” '_id':2 '孩子们': [ { '_id':3 '名称':'日志', '孩子们': [ { '_id':5, '名称':'uwsgi', '孩子们': [] } ] }, { '_id':4 '名称':'log2', '孩子们': [ { '_id': 6, '名称':'nginx', '孩子们': [ { '_id': 7, '名称':'错误', '孩子们': [] }, { '_id': 8, '名称', '访问权限', '孩子们': [] } ] } ] } ] } ] }

我尝试了类似的方法,但没有成功:

def insert_node(d, res): 如果不是 res.get("children"): 资源[“孩子”] = [] 如果 d["path"] == res["path"]: res[“孩子”].append(d) 别的: 对于 res["children"] 中的 c: 插入节点(d,c) 根=节点[0] 对于节点[1:]中的节点 插入节点(节点,根)

是否有一种经典的递归方式来填充嵌套的 dict 结构?

【问题讨论】:

    标签: python mongodb


    【解决方案1】:

    这可能会解决它吗?

    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)
    

    【讨论】:

      猜你喜欢
      • 2019-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多