schmiddl
schmiddl

Reputation: 95

Python: Create directory tree from nested list of dictionaries

How can I create a directory tree from the below list of dictionaries in python? The number of subdirectory levels has to be variable.

dirTree: 
    [{'level-1_dir-1': ''}, 
    {'level-1_dir-2': 
        [{'level-2_dir-1': 
            [{'level-3_dir-1': ''}, 
            {'level-3_dir-2': ''}, 
            {'level-3_dir-3': ''}
            ]
        }, 
        {'level-2_dir-2': ''}
        ]
    }, 
    {'level-1_dir-3': ''}, 
    {'level-1_dir-4': ''}
    ]

I would like to accomplish something like the following tasks with python:

Upvotes: 0

Views: 401

Answers (1)

azro
azro

Reputation: 54148

You may recursivly create the dir, with the appropriate way regarding your structure

def createPath(values, prefix=""):
    for item in values:
        directory, paths = list(item.items())[0]
        dir_path = join(prefix, directory)
        makedirs(dir_path, exist_ok=True)
        createPath(paths, dir_path)

Call like createPath(dirTree) or createPath(dirTree, "/some/where) to choose the initial start


A simplier structure with only dicts would be more usable, because a dict for one mapping only is not very nice

res = {
    'level-1_dir-1': '',
    'level-1_dir-2':
        {
            'level-2_dir-1':
                {
                    'level-3_dir-1': '',
                    'level-3_dir-2': '',
                    'level-3_dir-3': ''
                },
            'level-2_dir-2': ''
        },
    'level-1_dir-3': '',
    'level-1_dir-4': ''
}

# with appropriate code
def createPath(values, prefix=""):
    for directory, paths in values.items():
        dir_path = join(prefix, directory)
        makedirs(dir_path, exist_ok=True)
        if isinstance(paths, dict):
            createPath(paths, dir_path)

Upvotes: 3

Related Questions