如何修改深度可变的嵌套Python字典中的指定值?
实现任意深度嵌套字典的指定值修改
你示例中的
path使用了集合{},但集合是无序结构,会导致路径的键顺序错乱,无法定位到正确节点,需要先把path替换为有序的列表/元组类型。另外depth参数可以直接通过len(path)获取,不需要额外传入。
基础实现(无自动建路)
如果路径必然存在,不需要处理中间键缺失的场景,直接用循环遍历即可:
def change_item(nested_dict: dict, path: list | tuple, new_value) -> None: # 迭代到目标键的上一级字典 current = nested_dict for key in path[:-1]: current = current[key] # 对目标键赋值 current[path[-1]] = new_value
使用示例
myfamily = { "child1" : { "name" : "Emil", "year" : 2004, "grandchild1" : { "name" : "Emil", "year" : 2004 } }, "child2" : { "name" : "Tobias", "year" : 2007 }, "child3" : { "name" : "Linus", "year" : 2011 } } # 修改 child1 -> grandchild1 -> name 的值为 Tom path = ["child1", "grandchild1", "name"] change_item(myfamily, path, "Tom") # 验证修改结果 print(myfamily["child1"]["grandchild1"]["name"]) # 输出 Tom
增强实现(自动创建不存在的路径)
如果允许中间路径不存在时自动创建嵌套字典,可以修改循环逻辑:
def change_item_auto_create(nested_dict: dict, path: list | tuple, new_value) -> None: current = nested_dict for key in path[:-1]: # 键不存在或者对应值不是字典时,自动创建空字典 if key not in current or not isinstance(current[key], dict): current[key] = {} current = current[key] current[path[-1]] = new_value
简洁写法(基于reduce实现)
如果追求代码简洁,可以用functools.reduce简化循环逻辑:
from functools import reduce import operator def change_item_reduce(nested_dict: dict, path: list | tuple, new_value) -> None: parent_dict = reduce(operator.getitem, path[:-1], nested_dict) parent_dict[path[-1]] = new_value
内容的提问来源于stack exchange,提问作者Sebrotec
相关产品推荐
相关产品推荐

