mongodb - Python/ materialized paths: recursively create nested dict from flat list -
i'm trying create nested dict construction flat list of dicts contain path string, mongodb in order build tree displayed in d3. instance, here illustration set of data:
[ { "_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/" } ]i need info sort of format of nodes name attribute , list of children chart display
{ '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': [] } ] } ] } ] } ] }i tried did not work:
def insert_node(d, res): if not res.get("children"): res["children"] = [] if d["path"] == res["path"]: res["children"].append(d) else: c in res["children"]: insert_node(d, c) root = nodes[0] node in nodes[1:] insert_node(node, root)is there classy recursive way populate nested dict structure?
possibly prepare it?
def insert_node(d, res): if not res.get("children"): res["children"] = [] if d["path"] == res["path"]+res['name']+'/': res["children"].append(d) else: c in res["children"]: insert_node(d, c) root = nodes[0] node in nodes[1:] insert_node(node, root)
python mongodb
No comments:
Post a Comment