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?

kamaru510
  • 25
  • 3
  • _What_ are you finding challenging? Please read [ask] and the [question checklist](//meta.stackoverflow.com/q/260648/843953), and ask a _specific_ question about your issue. It helps to include a [mre]. – Pranav Hosangadi Jul 26 '22 at 16:27
  • Duplicate of https://stackoverflow.com/questions/14692690/access-nested-dictionary-items-via-a-list-of-keys – Pranav Hosangadi Jul 26 '22 at 16:28

2 Answers2

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': {}}}}
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
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.

Savvii
  • 480
  • 4
  • 9