2

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]
0

2 Answers 2

4

Here's a very rough algorithm:

  • For each string in the list:
    • Split it into path components
    • For each component:
      • Check if there's a tree node of that name at the current level, else create it
      • If non-leaf, make the node just visited (or created) the current one
Sign up to request clarification or add additional context in comments.

1 Comment

Good enough. How to check the tree node?
4

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': {}}}

1 Comment

Impressive use of setdefault !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.