Lakhu Ambaliya Lakhu Ambaliya - 6 months ago 36
Python Question

converting list of dictionary to dictionary tree based on parent id

I want to make a list of dictionary that way, every element which has a parent id, it should be child of the parent element.

Let's say we have a python list, which contains multiple dictionaries.

[{
"id": 1,
"title": "node1",
"parent": null
},
{
"id": 2,
"title": "node2",
"parent": 1
},
{
"id": 3,
"title": "node3",
"parent": 1
},
{
"id": 4,
"title": "node4",
"parent": 2
},
{
"id": 5,
"title": "node5",
"parent": 2
}]


And I want to convert this list to tree based on parent key. like,

[{
'id':1,
'title':'node1',
'childs':[
{
'id':2,
'title':'node2'
'childs':[
{
'id':4,
'title':'node4',
'childs': []
},
{
'id':5,
'title':'node5',
'childs': []
}
]
},
{
'id':3,
'title':'node3'
'childs':[]
}
]
}]

Answer
data = [{
  "id": 1,
  "title": "node1",
  "parent": "null"
  },
  { "id": 2,
    "title": "node2",
    "parent": "null"
  },
{
    "id": 2,
    "title": "node2",
    "parent": 1
},
{
    "id": 3,
    "title": "node3",
    "parent": 1
},
{
    "id": 4,
    "title": "node4",
    "parent": 2
},
{
    "id": 5,
    "title": "node5",
    "parent": 2
}]
parent_data=[]
for keys in data:
  if keys['parent'] == "null":
     keys['childs']=[]
     parent_data.append(keys)

for keys in data:
  for key in parent_data:
     if key['id'] == keys['parent']:
         key['childs'].append(keys)



print parent_data