Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 293
Boris Gorelik Avatar asked Apr 05 '11 12:04

Boris Gorelik


People also ask

How do I make a deep copy of a dictionary?

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.

How do I copy a key value pair to another dictionary in Python?

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.


1 Answers

The simplest way in my opinion is something like this:

new_dict = {**old_dict, 'changed_val': value, **other_new_vals_as_dict} 
like image 58
Denis Kim Avatar answered Sep 18 '22 08:09

Denis Kim