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

后端 未结 9 1015
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-29 00:50

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, 
            \'param         


        
9条回答
  •  渐次进展
    2020-12-29 01:37

    setup2 = dict((k, {'param1': val10, 'param2': val20}.get(k, v))
                  for k, v in setup1.iteritems())
    

    This only works if all keys of the update dictionary are already contained in setup1.

    If all your keys are strings, you can also do

    setup2 = dict(setup1, param1=val10, param2=val20)
    

提交回复
热议问题