Search code examples
pythondata-structuresdynatree

Creating nested python dictionary for Dynatree


The dynatree jquery tree element can read from the following format:

{'title':'a','children':[{'title':'b','children':[{'title':'c','children':[]}]}]}

I have a path a:b:c.

How to generate nested python dictionary, given above, that will use the given path?

I have a lot of different paths some of them repeat 'a:b:c:d', adding new element, some of

them completely different?


Solution

  • Split the path by : and start from the last element, encapsulating each one into its container:

    def path_to_tree(p):
        elems = p.split(':')
        head = None
        for elem in reversed(elems):
            head = {'title': elem, 'children': [] if head is None else [head]}
        return head