Skip to content
Advertisement

Replace a value in a nested dictionary by following a certain path to value in Python

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.

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement