'How do I update value in a nested dictionary given a path

I have a nested dictionary

nested_dictionary = {
    "a": { "1": 1, "2": 2, "3": 3 },
    "b": { "4": 4, "5": 5, "6": {"x": 10, "xi": 11, "xii": 13}}
    }

I am wondering if there is any way I can update the value in the nested value

path = ["b", "6", "xii"]
value = 12

so that the nested dictionary would be updated to

updated_nested_dictionary = {
    "a": { "1": 1, "2": 2, "3": 3 },
    "b": { "4": 4, "5": 5, "6": {"x": 10, "xi": 11, "xii": 12}}
    }

Thanks.



Solution 1:[1]

You can write an update function to recursively find a value and update it for you:

def update(path=["b", "6", "xii"], value=12, dictionary=nested_dictionary):
    """
    Update a value in a nested dictionary.
    """
    if len(path) == 1:
        dictionary[path[0]] = value
    else:
        update(path[1:], value, dictionary[path[0]])

    return dictionary

Solution 2:[2]

This can be done either recursively or, as here, iteratively:

nested_dictionary = {
    "a": {"1": 1, "2": 2, "3": 3},
    "b": {"4": 4, "5": 5, "6": {"x": 10,
                                "xi": 11,
                                "xii": 13
                                }
          }
}

def update_dict(d, path, value):
    for p in path[:-1]:
        if (d := d.get(p)) is None:
            break
    else:
        d[path[-1]] = value

update_dict(nested_dictionary, ['b', '6', 'xii'], 12)

print(nested_dictionary)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 osbm
Solution 2 Albert Winestein