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

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

    You can write your own class using UserDict wrapper, and simply add dicts like

    # setup1 is of Dict type (see below)
    setup2 = setup1 + {'param1': val10}
    

    All you have to do is

    • Define a new class using UserDict as base class
    • Implement __add__ method for it.

    Something like :

    class Dict(dict):
        def __add__(self, _dict):
            if isinstance(_dict, dict):
                tmpdict = Dict(self)
                tmpdict.update(_dict)
                return tmpdict
    
            else:
                raise TypeError
    
        def __radd__(self, _dict):
             return Dict.__add__(self, _dict)

提交回复
热议问题