Search code examples
pythondictionarynested

Create a nested dictionary from multiple lists in python


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?


Solution

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