Replace a value in a nested dictionary by following a certain path to value in Python
Question:
I have a nested dictionary that I’m trying to replace a given value of a key using a path made up of keys to that particular value.
Basic Example:
path_to_value = ["fruit", "apple", "colour"]
replacement_value = "green"
dictionary = {"fruit": {"apple": {"colour": "red"}, "banana": {"colour": "yellow", "size": "big"}}}
I’ve found a function here on Stackoverflow, but it recursively replaces all values in the dict which I don’t want.
def change_key(d, required_key, new_value):
for k, v in d.items():
if isinstance(v, dict):
change_key(v, required_key, new_value)
if k == required_key:
d[k] = new_value
Any help would be appreciated.
Answers:
I think something like this should work: narrow in using all but the last keys to get the dictionary you want to modify, then modify it using the last key.
def change_key(d, path_to_value, new_value):
for key in path_to_value[:-1]:
d = d[key]
d[path_to_value[-1]] = new_value
you cay try this:
def replace_val(dict, val_path, new_val):
if len(val_path) == 1:
dict[val_path[0]] = new_val
return dict
else:
dict[val_path[0]] = replace_val(dict[val_path[0]], val_path[1:], new_val)
return dict
I have a nested dictionary that I’m trying to replace a given value of a key using a path made up of keys to that particular value.
Basic Example:
path_to_value = ["fruit", "apple", "colour"]
replacement_value = "green"
dictionary = {"fruit": {"apple": {"colour": "red"}, "banana": {"colour": "yellow", "size": "big"}}}
I’ve found a function here on Stackoverflow, but it recursively replaces all values in the dict which I don’t want.
def change_key(d, required_key, new_value):
for k, v in d.items():
if isinstance(v, dict):
change_key(v, required_key, new_value)
if k == required_key:
d[k] = new_value
Any help would be appreciated.
I think something like this should work: narrow in using all but the last keys to get the dictionary you want to modify, then modify it using the last key.
def change_key(d, path_to_value, new_value):
for key in path_to_value[:-1]:
d = d[key]
d[path_to_value[-1]] = new_value
you cay try this:
def replace_val(dict, val_path, new_val):
if len(val_path) == 1:
dict[val_path[0]] = new_val
return dict
else:
dict[val_path[0]] = replace_val(dict[val_path[0]], val_path[1:], new_val)
return dict