简体   繁体   中英

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.

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM