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.
CodePudding user response:
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
CodePudding user response:
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)