Mike Bourbeau Mike Bourbeau - 6 months ago 60
Python Question

Merge nested dictionaries by appending

I'm trying to automate menu creation for my CG pipeline. I have a lot of scripts and maintaining the pipeline by hand is becoming cumbersome. I'd like to just put a nested dictionary variable in each module that will have the hierarchy of the menu item- it would tell the menu builder script where to put menu item.

Basically, I'm having trouble figuring out how to merge dictionaries like so:

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'
}
}
}


The output would look like this:

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'
}
}
}


I've tried update, but it seems to overwrite values. I've tried a bunch of the recursive function examples on here, but haven't found an example for deeply nested dictionaries (only single nest). I'd like something more dynamic than those hard coded examples. I'm also contemplating continuing with this direction because I'm unsure if this is even possible, so some confirmation on that would be helpful as well. Thanks!

Answer Source

Try this function:

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download