I have list of directory structure such as:
['/a/b', '/a/b/c', '/a/b/c/d', '/a/b/c/e', '/a/b/c/f/g', '/a/b/c/f/h', '/a/b/c/f/i']
I want to convert it into dict like a tree structure.
{'/': {'a': {'b': {'c':
[{'d':None},
{'e':None},
{'f':[{'g':None, {'h':None}, {'i':None}]}
]
}
}
}
}
I got stuck where to strat ? Which data structure will be suitable?
Thanks.
A list can contain another list. A dictionary can contain another dictionary. A dictionary can also contain a list, and vice versa.
basically
lst = ['/a/b', '/a/b/c', '/a/b/c/d', '/a/b/c/e', '/a/b/c/f/g', '/a/b/c/f/h', '/a/b/c/f/i']
dct = {}
for item in lst:
p = dct
for x in item.split('/'):
p = p.setdefault(x, {})
print dct
produces
{'': {'a': {'b': {'c': {'e': {}, 'd': {}, 'f': {'i': {}, 'h': {}, 'g': {}}}}}}}
this is not exactly your structure, but should give you a basic idea.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With