python-3.x - 在python中使用相同的键合并两个字典
问题描述
我想用相同的键在python中合并两个字典
字典:
dict1 = { 'a1': { 'b1': { 'c1': 'd1' }}}
dict2 = { 'a1': { 'b1': { 'c2': 'd2' }}}
dict3 = { 'a1': { 'b2': { 'c3': 'd3' }}}
dict4 = { 'a2': { 'b3': { 'c4': 'd4' }}}
我希望这个合并到
dict1 = {'a1': {'b1': {'c1': 'd1', 'c2': 'd2'}, 'b2': {'c3': 'd3'}},
'a2': {'b3': {'c4': 'd4'}}}
我尝试过合并,update
但它覆盖了所有内容
提前致谢。
编辑:
我试过的代码:
dict1.update(dict2)
dict1.update(dict3)
dict1.update(dict4)
输出:
>>> dict1
{'a1': {'b1': {'c2': 'd2'}}, 'a2': {'b3': {'c4': 'd4'}}}
解决方案
问题update
只在顶层有效。
def addin( d1, d2 ):
for k,v in d2.items():
if k not in d1:
d1[k] = v
else:
addin( d1[k], v )
merged = {}
addin( merged, dict1 )
addin( merged, dict2 )
addin( merged, dict3 )
addin( merged, dict4 )
print(merged)
推荐阅读
- html - 如何以响应方式定位 6 个引导容器?
- playframework - 如何在 conf 文件夹以及特殊的 conf 文件位置中进行查看?
- c++ - 我有一个创建另一个类的实例的类。如何通过第一类将变量传递到第二类的实例化中?
- node.js - Google App Engine Nodejs flex,它是否利用实例的所有核心,还是我必须手动创建流程?
- java - 三元运算符在这个递归代码中是如何工作的?
- julia - 使用微分方程:你没有更新
- emacs - 在运行函数之前自动加载建议需要文件
- java - Java:数组的可能组合
- list - 计算有序列表中的元素
- python - 获取python列表中的所有项目?