Python中如何递归替换/更新嵌套字典的键值对?
递归更新嵌套字典的所有层级键值对
问题场景
现有嵌套字典:
mydict = { "name": "Bill", "gender": "Male", "facts": {"age": 20, "location": "England"} }
使用from dataclasses import replace可以处理顶层键的更新(比如to_replace = {"name": "Billy Kidman", "gender": "Female"}),但如果更新字典包含嵌套子字典中的键(比如to_replace_2 = {"name": "Billy Kidman", "gender": "Female", "age": 55}),replace方法会直接报错——它无法识别嵌套层级的键。要求不修改to_replace_2的扁平格式,实现递归查找并替换所有层级的对应键值。
解决方案:递归更新函数
写一个递归函数遍历字典的每一层级,匹配到更新字典中的键就替换对应值:
def recursive_update(target_dict, updates): # 遍历所有要更新的键值对 for key, new_val in updates.items(): # 当前层级存在该键则直接替换 if key in target_dict: target_dict[key] = new_val else: # 遍历当前字典的所有值,遇到子字典就递归查找 for nested_key, nested_val in target_dict.items(): if isinstance(nested_val, dict): recursive_update(nested_val, {key: new_val}) return target_dict
使用示例
mydict = { "name": "Bill", "gender": "Male", "facts": {"age": 20, "location": "England"} } to_replace_2 = {"name": "Billy Kidman", "gender": "Female", "age": 55} # 使用copy()避免修改原字典 updated_dict = recursive_update(mydict.copy(), to_replace_2) print(updated_dict)
执行后输出:
{'name': 'Billy Kidman', 'gender': 'Female', 'facts': {'age': 55, 'location': 'England'}}
函数说明
- 优先处理当前层级的键,找到则直接替换
- 当前层级没找到目标键时,自动遍历所有子字典并递归进入查找替换
- 支持任意深度的嵌套字典,不需要调整更新字典的格式
内容的提问来源于stack exchange,提问作者BBB
相关产品推荐
相关产品推荐

