python - 如何在不破坏的情况下合并两个字典
问题描述
我有两本字典,我想将它们组合起来。
dict1 = {'abc': {'test1': 123}}
dict2 = {'abc': {'test2': 456}}
我想结束
{'abc': {'test1': 123, 'test2': 456}}
如果dict2 = {'abc': 100}
那时我想要:
{'abc' 100}
我试过dict1.update(dict2)
了,但这给了我{'abc': {'test2': 456}}
有没有一种pythonic方法可以做到这一点?
解决方案
IIUC,您可以执行以下操作:
def recursive_update(d1, d2):
"""Updates recursively the dictionary values of d1"""
for key, value in d2.items():
if key in d1 and isinstance(d1[key], dict) and isinstance(value, dict):
recursive_update(d1[key], value)
else:
d1[key] = value
dict1 = {'abc': {'test1': 123}}
dict2 = {'abc': {'test2': 456}}
recursive_update(dict1, dict2)
print(dict1)
输出
{'abc': {'test1': 123, 'test2': 456}}
请注意,递归仅适用于作为字典的值。例如:
dict1 = {'abc': {'test1': 123}}
dict2 = {'abc': 100}
产生(如预期):
{'abc': 100}
推荐阅读
- java - 反序列化 Yaml 对象列表
- javascript - 如何使用其名称获取文件(位于本地计算机的文件夹中)并使用 Node.js 在浏览器中下载它
- flutter - 将数据添加到websocket时如何在小部件中添加删除和显示?
- css - @font-face 不会对页面应用任何字体
- html - 使用 CSS 删除 html 类
- c# - 与子弹碰撞时尝试触发动画
- python - 使用 Selenium Python 下载文件时出现“失败 - 下载错误”
- go - 是return nil,nil不是惯用的吗?
- c# - 从组合框中获取绑定的选定项目
- java - 为什么我们需要使用线程来运行 Kafka 消费者?我们需要多少线程?