Recursive function for trees in Python
The problem is here
if node['id'] == parent:
parent = node['parent']
The current parent
will be overwritten by its parent.
Moreover, you should add return node_list
at the end of the function, or use node_list
as results.
def pop_list(nodes=None, parent=None, node_list=None):
if parent is None:
return node_list
node_list.append([])
for node in nodes:
if node['parent'] == parent:
node_list[-1].append(node)
if node['id'] == parent:
next_parent = node['parent']
pop_list(nodes, next_parent, node_list)
return node_list
>>> print pop_list(nodes, 5, node_list)
[[{'id': 6, 'parent': 5}], [{'id': 4, 'parent': 2}, {'id': 5, 'parent': 2}], [{'id': 2, 'parent': 1}, {'id': 3, 'parent': 1}]]