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

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

    Solution

    Build a function for that.

    Your intention would be clearer when you use it in the code, and you can handle complicated decisions (e.g., deep versus shallow copy) in a single place.

    def copy_dict(source_dict, diffs):
        """Returns a copy of source_dict, updated with the new key-value
           pairs in diffs."""
        result=dict(source_dict) # Shallow copy, see addendum below
        result.update(diffs)
        return result
    

    And now the copy is atomic, assuming no threads involved:

    setup2=copy_dict(setup1, {'param1': val10, 'param2': val20})
    

    Addendum - deep copy

    For primitives (integers and strings), there is no need for deep copy:

    >>> d1={1:'s', 2:'g', 3:'c'}
    >>> d2=dict(d1)
    >>> d1[1]='a'
    >>> d1
    {1: 'a', 2: 'g', 3: 'c'}
    >>> d2
    {1: 's', 2: 'g', 3: 'c'}
    

    If you need a deep copy, use the copy module:

    result=copy.deepcopy(source_dict) # Deep copy
    

    instead of:

    result=dict(setup1)               # Shallow copy
    

    Make sure all the objects in your dictionary supports deep copy (any object that can be pickled should do).

提交回复
热议问题