P
P
pcdesign2020-07-14 09:23:10
Python
pcdesign, 2020-07-14 09:23:10

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
  }
]


How to add a list of all IDs that are nested so that it looks like this:

[
  {
    "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

2 answer(s)
P
pcdesign, 2020-07-15
@pcdesign

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'], [])

Result:
[{'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': []}]

M
Maxim, 2020-07-14
@Tomio

lst = [
  {
    "id":1,
    "parent":""
  },
  {
    "id":2,
    "parent":1
  },
  {
    "id":3,
    "parent":1
  },
  {
    "id":4,
    "parent":3
  },
  {
    "id":5,
    "parent":3
  }
]

for item in lst:
    item.update({'sub_ids': [sub['id'] for sub in lst if sub['parent'] == item['id']]})

print(lst)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question