Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse a directory structure into dictionary?

Tags:

python

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.

like image 559
user12345 Avatar asked Mar 08 '12 14:03

user12345


People also ask

Can a dict contain a list?

A list can contain another list. A dictionary can contain another dictionary. A dictionary can also contain a list, and vice versa.


1 Answers

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.

like image 88
georg Avatar answered Sep 18 '22 00:09

georg