[英]Merging dictionaries in Python - doesn't work as expected
我正在尋找一種通過dict(a.items()+b.items())
以外的其他方式合並字典的方法。
例:
foo = {'cart':
{'item':
{'1':
{'amount':
'X',
},
},
},
}
bar = {'cart':
{'item':
{'2':
{'amount':
'Y',
},
},
},
}
想要的結果:
res = {'cart':
{'item':
{'1':
{'amount':
'X'
},
},
{'2':
{'amount':
'Y',
},
},
},
}
實際結果(獲得的貝塔dict(foo.items()+ bar.items()):
res = {'cart':
{'item':
{'2':
{'amount':
'Y',
},
},
},
}
在此先多謝!
找到了適合我的用例的代碼片段:
def deepupdate(original, update):
"""
Recursively update a dict.
Subdict's won't be overwritten but also updated.
"""
for key, value in original.iteritems():
if not key in update:
update[key] = value
elif isinstance(value, dict):
deepupdate(value, update[key])
return update
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.