I have table that looks like this:
id | parentid | name
---------------------
1 | 0 | parent1
---------------------
2 | 0 | parent2
---------------------
3 | 1 | child1
---------------------
4 | 3 | subchild1
I'm now trying to come up with an efficient way to take that database data and create a Python dictionary.
Basically, I want to be able to do:
tree = expand(Session.query(mytable).all())
print tree['parent2']['child2']
# result would be 'subchild1'
I'm at a complete loss with how to do this... I've been messing around with the following function but I can't get it working. Any help would be appreciated.
def expand(tree):
parents = [i for i in tree if i.parentid == 0]
for parent in parents:
children = expand(parent)