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

后端 未结 9 946
佛祖请我去吃肉
佛祖请我去吃肉 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:38
    setup2 = dict(setup1.items() + {'param1': val10, 'param2': val20}.items())
    

    This way if new keys do not exist in setup1 they get added, otherwise they replace the old key/value pairs.

    0 讨论(0)
  • 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).

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题