1

Let us assume to have the following tree structure:

a = [(1, 2), (2, 2), (3, 2), (4, 2), (5, 4), (6, 5), (7, 8), (8, 11), (9, 10), (10, 11), (11, 11)]

so we get with this code Python - Generate a dictionary(tree) from a list of tuples the structure

[{'id': 2, 'Children': [{'id': 1}, {'id': 3}, {'id': 4, 'Children': [{'id': 5, 'Children': [{'id': 6}]}]}]}, {'id': 11, 'Children': [{'id': 8, 'Children': [{'id': 7}]}, {'id': 10, 'Children': [{'id': 9}]}]}]

my question: how can I take all children of a special node of this dictionary? for example: all the children of 11 are: (7, 8, 9, 10) what to do?

Rakesh
  • 81,458
  • 17
  • 76
  • 113
FKAT
  • 11
  • 1

1 Answers1

0

You can use recursion with a generator to find the desired children of a node. First, for easier lookup later, use recursion to restructure the tree:

data = [{'id': 2, 'Children': [{'id': 1}, {'id': 3}, {'id': 4, 'Children': [{'id': 5, 'Children': [{'id': 6}]}]}]}, {'id': 11, 'Children': [{'id': 8, 'Children': [{'id': 7}]}, {'id': 10, 'Children': [{'id': 9}]}]}]
def rebuild(d):
  return {i['id']:None if 'Children' not in i else rebuild(i['Children']) for i in d}

result = rebuild(data)

Now, apply a recursive generator function:

def get_children(d):
  for a, b in d.items():
    yield a
    if isinstance(b, dict):
       yield from get_children(b)

print(sorted(get_children(result[11])))

Output:

[7, 8, 9, 10]
Ajax1234
  • 69,937
  • 8
  • 61
  • 102