Skip to content
Advertisement

How to copy a dict and modify it in one line of code

Very often I need to create dicts that differ one from another by an item or two. Here is what I usually do:

setup1 = {'param1': val1, 
            'param2': val2,
            'param3': val3,
            'param4': val4,
            'paramN': valN}

setup2 = copy.deepcopy(dict(setup1))
setup2.update({'param1': val10, 
                   'param2': val20})

The fact that there is a point in the program at which setup2 is an identical copy of setup1 makes me nervous, as I’m afraid that at some point of the program life the two lines might get separated, which is a slippery slope towards too many bugs.

Ideally I would like to be able to complete this action in a single line of code (something like this):

setup2 = dict(setup1).merge({'param1': val10, 
                        'param2': val20})

Of course, I can use semicolon to squeeze two commands into one physical line, but this looks pretty ugly to me. Are there other options?

Advertisement

Answer

The simplest way in my opinion is something like this:

new_dict = {**old_dict, 'changed_val': value, **other_new_vals_as_dict}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement