Python中有没有一个可以用来深度合并字典的库:
以下内容:
a = { 'first' : { 'all_rows' : { 'pass' : 'dog', 'number' : '1' } } }
b = { 'first' : { 'all_rows' : { 'fail' : 'cat', 'number' : '5' } } }当我组合的时候,我希望它看起来像这样:
a = { 'first' : { 'all_rows' : { 'pass' : 'dog', 'fail' : 'cat', 'number' : '5' } } }发布于 2013-12-19 03:04:46
我希望我不会重复发明轮子,但解决方案相当简短。而且,编写代码非常有趣。
def merge(source, destination):
"""
run me with nosetests --with-doctest file.py
>>> a = { 'first' : { 'all_rows' : { 'pass' : 'dog', 'number' : '1' } } }
>>> b = { 'first' : { 'all_rows' : { 'fail' : 'cat', 'number' : '5' } } }
>>> merge(b, a) == { 'first' : { 'all_rows' : { 'pass' : 'dog', 'fail' : 'cat', 'number' : '5' } } }
True
"""
for key, value in source.items():
if isinstance(value, dict):
# get node or create one
node = destination.setdefault(key, {})
merge(value, node)
else:
destination[key] = value
return destination所以我们的想法是将源文件复制到目标文件中,每次在源文件中出现字典时,就会递归。因此,如果在A中,给定的元素包含一个dict,而在B中包含任何其他类型,那么你确实会有一个bug。
按照评论中所说的那样编辑解决方案已经在这里:https://stackoverflow.com/a/7205107/34871
https://stackoverflow.com/questions/20656135
复制相似问题