如何更新 python 字典的多个子值?

How to update python dictionary multiple sub values?

我有以下具有默认值的 Python 2.7.16 字典:

settings = {
    'alpha': {
        'Add': [],
        'Delete': [],
        'Patch': {
            'Software': False,
            'Hardware': False
        }
    },
    'beta': {
        'Flash': [],
        'Definitions': {
            'Occur': False,
            'Define': False,
            'Disable': False,
            'Enable': False
        }
    },
    'gamma': {
        'Allow': {},
        'Block': {}
    }
}

我想用新字典中的值更新 settings 字典,定义如下:

new_settings = {
    'alpha': {
        'Delete': ['model', 'structure'],
        'Patch': {
            'Software': True
        }
    },
    'beta': {
        'Definitions': {
            'Define': True,
            'Disable': True
        }
    },
    'gamma': {
        'Allow': {
            'Update': True
        }
    }
}

最终结果将是以下合并字典:

settings = {
    'alpha': {
        'Add': [],
        'Delete': ['model', 'structure'],
        'Patch': {
            'Software': True,
            'Hardware': False
        }
    },
    'beta': {
        'Flash': [],
        'Definitions': {
            'Occur': False,
            'Define': True,
            'Disable': True,
            'Enable': False
        }
    },
    'gamma': {
        'Allow': {
            'Update': True
        },
        'Block': {}
    }
}

我试过了:

configuration = settings.copy()
configuration.update(new_settings)

但这会导致某些键从 setting 字典中删除。

谢谢。

new_settings = {
        'alpha': {
            'Delete': ['model', 'structure'],
            'Patch': {
                'Software': True
            }
        },
        'beta': {
            'Definitions': {
                'Define': True,
                'Disable': True
            }
        },
        'gamma': {
            'Allow': {
                'Update': True
            }
        }
    }

    settings = {
        'alpha': {
            'Add': [],
            'Delete': [],
            'Patch': {
                'Software': False,
                'Hardware': False
            }
        },
        'beta': {
            'Flash': [],
            'Definitions': {
                'Occur': False,
                'Define': False,
                'Disable': False,
                'Enable': False
            }
        },
        'gamma': {
            'Allow': {},
            'Block': {}
        }
    }



    for key, value in new_settings.items():

        if value.__class__.__name__ == "dict":
        # check if element is a dictionary
            for key2, value2 in value.items():
                # if dictionary get key and value for that dictionary
                if value2.__class__.__name__ == "dict":
                    # check if there is nested dictionary
                    settings[key][key2].update(value2)
                    # if it exists update the lements within dictionary

                elif value.__class__.__name__ in ("list", "tuple"):
                    settings[key][key2] += value2
                    # check if there is inner list or tuple and combine

                else:
                    settings[key][key2] = value
                    # if inner value is string or numeric replace



        elif value.__class__.__name__ in ("list", "tuple"):
            # if first element is list or tuple combine
            settings[key] += value

        else:
            # if first element is string or numeric replace
            settings[key] = value


    # this should work perfect for 3 layerd dictionaries beyond that requires your own modifications
    print(settings)

您需要递归地更新嵌套字典,如下所示。

import collections

def update(d, u):
    for k, v in u.iteritems():
        if isinstance(v, collections.Mapping):
            d[k] = update(d.get(k, {}), v)
        else:
            d[k] = v

    return d

update(settings, new_settings)

print(settings)