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.

Asked By: nablue

||

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
Answered By: Dennis

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
Answered By: Ella_by
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.