Answer the question
In order to leave comments, you need to log in
How to iterate over the data structure and get all nested ids?
There is such a structure:
[
{
"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": []
}
]
Answer the question
In order to leave comments, you need to log in
Here is a solution using recursion. I don't like it, but I can't think of anything else:
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': []}]
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question