1

I have a list containing paths. For example:

links=['main',
 'main/path1',
 'main/path1/path2',
 'main/path1/path2/path3/path4',
 'main/path1/path2/path3/path5',
 'main/path1/path2/path3/path4/path6']

I want to create a nested dictionary to store these paths in order. Expected output:

Output = {‘main’: {‘path1’: {‘path2’: {‘path3’: {‘path4’: {‘path6’: {} }},‘path5’:{}}}}}

I am new to python coding (v 3.+) and I am unable to solve it. It gets confusing after i reach path 3 as there is path 4 (with path6 nested) and path5 as well. Can someone please help ?

bipll
  • 11,747
  • 1
  • 18
  • 32
Gary
  • 909
  • 8
  • 20

1 Answers1

3

Something like

tree = {}
for path in links:                # for each path
    node = tree                   # start from the very top
    for level in path.split('/'): # split the path into a list
        if level:                 # if a name is non-empty
            node = node.setdefault(level, dict())
                                  # move to the deeper level
                                  # (or create it if unexistent)

With links defined as above, it results in

>>> tree
{'main': {'path1': {'path2': {'path3': {'path4': {'path6': {}}, 'path5': {}}}}}}
bipll
  • 11,747
  • 1
  • 18
  • 32