[
{
"id":1,
"parent":""
},
{
"id":2,
"parent":1
},
{
"id":3,
"parent":1
},
{
"id":4,
"parent":3
},
{
"id":5,
"parent":3
}
]
[
{
"id":1,
"parent":"",
"sub_ids": [2, 3, 4, 5]
},
{
"id":2,
"parent":1,
"sub_ids": []
},
{
"id":3,
"parent":1,
"sub_ids": [4, 5]
},
{
"id":4,
"parent":3,
"sub_ids": []
},
{
"id":5,
"parent":3,
"sub_ids": []
}
]
def get_sub_ids(parent, arr):
for sub in my_list:
if sub['parent'] == parent:
arr.append(sub['id'])
get_sub_ids(sub['id'], arr)
return arr
for item in my_list:
item['sub_ids'] = get_sub_ids(item['id'], [])
[{'id': 1, 'parent': '', 'sub_ids': [2, 3, 4, 5]}, {'id': 2, 'parent': 1, 'sub_ids': []}, {'id': 3, 'parent': 1, 'sub_ids': [4, 5]}, {'id': 4, 'parent': 3, 'sub_ids': []}, {'id': 5, 'parent': 3, 'sub_ids': []}]