通过追加合并嵌套词典

时间:2017-11-30 01:59:16

标签: python dictionary nested

我试图为我的CG管道自动创建菜单。我有很多脚本,手工维护管道变得很麻烦。我想在每个模块中放置一个嵌套的字典变量,它将具有菜单项的层次结构 - 它将告诉菜单构建器脚本将菜单项放在何处。

基本上,我很难弄清楚如何合并这样的词典:

dict_1 = {
    'ROOT DIV A' : {
        'Root Menu A': {
            'SUB DIV A' : {
                'Sub Menu A':{
                    'command' : 'import commands',
                    'annotation' : 'some command'
                }
            }
        }
    }
}

dict_2 = {
    'ROOT DIV A' : {
        'Root Menu A': {
            'SUB DIV A' : {
                'Sub Menu B':{
                    'command' : 'import commands',
                    'annotation' : 'some command'
                }
            }
        }
    }
}

dict_3 = {
    'ROOT DIV A' : {
        'Root Menu B':{
            'command' : 'import commands',
            'annotation' : 'some command'
        }
    }
}

输出如下:

 result_dict = {
    'ROOT DIV A' : {
        'Root Menu A': {
            'SUB DIV A' : {
                'Sub Menu A':{
                    'command' : 'import commands',
                    'annotation' : 'some command'
                },
                'Sub Menu B':{
                    'command' : 'import commands',
                    'annotation' : 'some command'
                }
            }
        },
        'Root Menu B':{
            'command' : 'import commands',
            'annotation' : 'some command'
        }
    }
}

我尝试过更新,但它似乎覆盖了值。我在这里尝试了一堆递归函数示例,但是没有找到深层嵌套字典的示例(只有单个嵌套)。我喜欢比那些硬编码的例子更有活力的东西。我也在考虑继续这个方向,因为我不确定这是否可行,所以对此的一些确认也会有所帮助。谢谢!

1 个答案:

答案 0 :(得分:1)

尝试此功能:

def merge_dicts(x, y):    
    for key in y:
        if key in x:
            if isinstance(x[key], dict) and isinstance(y[key], dict):
                merge_dicts(x[key], y[key])
        else:
            x[key] = y[key]
    return x

result_dict = merge_dicts(merge_dicts(dict_1, dict_2), dict_3)
相关问题