简体   繁体   English

如何在给定路径的情况下更新嵌套字典中的值

[英]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:您可以编写一个update function 以递归地找到一个值并为您更新它:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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