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?
deepcopy() To make a deep copy, use the deepcopy() function of the copy module. In a deep copy, copies are inserted instead of references to objects, so changing one does not change the other.
By using dict. copy() method we can copies the key-value in a original dictionary to another new dictionary and it will return a shallow copy of the given dictionary and it also helps the user to copy each and every element from the original dictionary.
The simplest way in my opinion is something like this:
new_dict = {**old_dict, 'changed_val': value, **other_new_vals_as_dict}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With