0

I want to create a single dictionary from multiple lists containing filesystem paths.

Here are examples for the lists I want to convert:

list1 = ["root_path", "Test", "Subfolder1"]
list2 = ["root_path", "Test", "Subfolder2"]
list3 = ["root_path", "Test", "Subfolder3"]
list4 = ["root_path", "Test", "Subfolder1", "Subfolder1-1"]
list5 = ["root_path", "Test", "Subfolder1", "Subfolder1-1", "Subfolder1-1-1"]
..

The resulting dictionary should have this nested structure:

resulting_dict = {
        "root_path": {
            "Test": {
                "Subfolder1": {
                    "Subfolder1-1": {
                        "Subfolder1-1-1": {}
                    } 
                },
                "Subfolder2": {},
                "Subfolder3": {},
            }
        }
    }

Finding it really challenging. Any help?

2

2 Answers 2

1

Use setdefault to create the nested dictionaries:

# put the lists in a parent list to make iteration easier
lists = [list1, list2, list3, list4, list5]

# root dictionary
res = {}
for lst in lists:
    cursor = res  # point cursor to root dictionary
    for e in lst:
        cursor = cursor.setdefault(e, {})  # set the value to empty dictionary if not already set, return the value

print(res)

Output

{'root_path': {'Test': {'Subfolder1': {'Subfolder1-1': {'Subfolder1-1-1': {}}},
                        'Subfolder2': {},
                        'Subfolder3': {}}}}
Sign up to request clarification or add additional context in comments.

Comments

0

Problem solved

def mkdir(path: list, struct: dict):
    """
    recursively create directories
    """
    walker = walk(path)
    if not path: return 
    if struct == {}:
        new_dir = struct[path[0]] = {}
        return mkdir(path[1:], new_dir)
    for name, dir in struct.items():
        if name == path[0]:
            mkdir(path[1:], dir)
            break
    else:
        new_dir = struct[path[0]] = {}
        return mkdir(path[1:], new_dir)

USAGE

mkdir(folder_list, base_directory)

This function works like magic! It can nest hundreds of directories.

Comments

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.