2

I have a dictionary of settings of this kind of structure:

main_dict = {
    'a': {
        'a1': 1,
        'a2': 2,
    },
    'b': {
        'bb': {
            'bb1' : 1,
            'bb2' : 2,
        },
    },
}

I then have some classes which hold references to the dictionaries contained within main_dict, such as like this:

class B:
    def __init__(self, settings):
        self.settings = settings

my_b = B(main_dict['b'])
assert(my_b.settings is main_dict['b'])

So I can update the immutable values within main_dict and these updates will be reflected in my_b because my_b.settings is main_dict['b'].

However, I now have a new root dictionary with new settings in it following the same structure:

new_dict = {
    'a': {
        'a1': 11,
        'a2': 22,
    },
    'b': {
        'bb': {
            'bb1' : 11,
            'bb2' : 22,
        },
    },
}

Is there a simple and general purpose way to copy all of the immutable values in new_dict into main_dict such that the reference in my_b will be left intact?

4

1 回答 1

0

这会有帮助吗?

#!/usr/bin/env python3

def copyimmut(fromdict, todict):
    for key in fromdict:
        if type(fromdict[key]) is dict and key in todict:
            copyimmut(fromdict[key], todict[key])
        else:
            todict[key] = fromdict[key]

main_dict = {
    'a': {'a1': 1, 'a2': 2},
    'b': {'bb': {'bb1' : 1,'bb2' : 2, }}}

my_b = main_dict['b']
assert(my_b is main_dict['b'])
print(my_b)

new_dict = {
    'a': {'a1': 11, 'a2': 22},
    'b': {'bb': {'bb1' : 11, 'bb2' : 22, }},
    'c': {'cc': {'cc1' : 11, 'cc2' : 22, }}}

copyimmut(new_dict, main_dict)
assert(my_b is main_dict['b'])
print(my_b)
print(main_dict['c'])

产量

{'bb': {'bb1': 1, 'bb2': 2}}
{'bb': {'bb1': 11, 'bb2': 22}}
{'cc': {'cc2': 22, 'cc1': 11}}
于 2013-05-24T19:45:06.120 回答