I've got a Django model with a self-referencing foreign key, so my model (as a class in its most basic form) looks like:
class MyObj(object):
def __init__(self, id, ttl, pid):
self.id = id
self.name = ttl
self.parentid = pid
So a sample of my data might look like:
nodes = []
nodes.append(MyObj(1,'a',0))
nodes.append(MyObj(2,'b',0))
nodes.append(MyObj(3,'c',1))
nodes.append(MyObj(4,'d',1))
nodes.append(MyObj(5,'e',3))
nodes.append(MyObj(6,'f',2))
I've got to a point where I can convert this into a nested dictionary:
{'a': {'c': {'e': {}}, 'd': {}}, 'b': {'f': {}}}
using Converting tree list to hierarchy dict as a guide, but I need it in a form that I can use for Django's unordered_list filter.
So my question is, how can I get from (either) a nested dictionary to a nested list/tuple or straight from the source data to a nested list? I can't seem to get a recursive function to nest the lists correctly (as in a list I can't reference "sub trees" by name)
eval(string_rep_of_dictionary.replace(':',',').replace('{','[').replace('}',']')) seems to just about get me there but that seems a horrible solution?