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

后端 未结 9 1004
佛祖请我去吃肉
佛祖请我去吃肉 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:45

    If you just need to create a new dict with items from more than one dict, you can use:

    dict(a.items() + b.items())
    

    If both "a" and "b" have some same key, the result will have the value from b. If you're using Python 3, the concatenation won't work, but you can do the same by freezing the generators to lists, or by using the itertools.chain function.

提交回复
热议问题