Generate a nested list with a loop function [solved]

Hi everyone,

I have entries in a DB that have a parent-child relation.
In the DB each entry have a field with their parent id.

I would like to create a simple looping function that generate a nested list of those relation

DB

id parent name
1 None John
2 1 David
3 2 Grunt
4 1 Bob

Relations:

John
+---Bob
\---David
    \---Grunt

I have already a simple function that return a list of tuples when given an id
def returningchilds(Target_id):
   #omitted to simplify reading

returningchilds(1)

>>> [ (2, 'David' ), (4, 'Bob') ]

Then David have also a child and I would like to loop those too.

and have as final result a nested list


[  [1, 'John', [ [4, 'Bob', None ], [2, 'David', [ [ 3, 'Grunt' ] ] ] ]  ]

BTW
the argument of returningchilds() can be changed and accept the same format has is output to simplify the loop.

Any ideas ?

Thanks.

All you need is a method whether BFS or DFS
BFS: Breadth-first search
DFS: Depth-first search

and the implement is based on what your database is and which driver you use

Hi !

For a quick and dirty solution re-using what you already have, you could try a recursive approach. The pseudo-code would be something like:

def returningchilds(Target_id):
    direct_children = ... # Uses the code you already have
    ret = list()
    for id_ in direct_children:
        children = returningchilds(id_)
        if children:
            ret.append([id_, children])
        else:
            ret.append([id_, None])
    return ret

Basically, it re-runs returningchilds for each detected direct child for the given id. Note that I use the id_ variable in a generic way, it can represent just the index or the index + the name depending on the location in the code. Also note that it’s a quick-and-dirty solution, there would be tons ow ways to improve it and make it more robust.

I’m not familiar with database management in Python, but I assume there must be plenty of helpful libraries for this application. Maybe someone else will orient you towards such solutions.

1 Like

Thank you very much @WeisLeDocto ,

Based on your example I’ve create a similar recursive function that give me the desired output :+1: