Need to turn x:
X = [['A', 'B', 'C'], ['A', 'B', 'D']]
Into Y:
Y = {'A': {'B': {'C','D'}}}
More specifically, I need to create a tree of folders and files from a list of absolute paths, which looks like this:
paths = ['xyz/123/file.txt', 'abc/456/otherfile.txt']
where, each path is split("/")
, as per ['A', 'B', 'C']
in the pseudo example.
As this represents files and folders, obviously, on the same level (index of the array) same name strings can't repeat.
Assuming that
{'C', 'D'}
meansset(['C', 'D'])
and your Python version supportsdict comprehension
andset comprehension
, here's an ugly but working solution:As for your example:
But please don't use it in a real-world application :)
UPDATE: here's one that works with arbitrary depths:
There is a logical inconsistency in your problem statement. If you really want
['xyz/123/file.txt', 'abc/456/otherfile.txt']
to be changed to
{'xyz': {'123': 'file.txt}, 'abc': {'456': 'otherfile.txt'}}
Then you have to answer how a path 'abc.txt' with no leading folder would be inserted into this data structure. Would the top-level dictionary key be the empty string
''
?This leaves us with d containing
{'A': {'B': {'C': {}, 'D': {}}}, 'W': {'Y': {'Z': {}}, 'X': {}}}
. Any item containing an empty dictionary is either a file or an empty directory.This should be pretty close to what you need:
Results in: