Reputation: 7752
I have a dynamic list which might look like this:
['test_data/reads1.fq', 'test_data/reads_2.fq', 'test_data/new_directory/ok.txt',
'test_data/new_directory/new_new_dir/test.txt', 'hello/hello1.txt'] and so on
I want to construct hierarchy tree structure from this file:
test_data
files
new_directory
file
new_new_dir
file
hello
How can I do this in Python?
Following code will construct list to the root of the file. How can I proceed after that?
[i.split('/') for i in a]
Upvotes: 2
Views: 145
Reputation: 185962
You can build a hierarchy quite simply as follows:
t = {}
for p in pp:
tt = t
for c in p.split('/'):
tt = tt.setdefault(c, {})
The only catch is that leaves are represented as keys with empty dictionaries:
{'test_data': {'reads1.fq' : {},
'reads_2.fq' : {},
'new_directory': {'ok.txt' : {},
'new_new_dir': {'test.txt': {}}}},
'hello' : {'hello1.txt': {}}}
Upvotes: 4
Reputation: 399959
Here's a very rough algorithm:
Upvotes: 4