How do I merge dictionaries together in Python?

后端 未结 7 1812
无人及你
无人及你 2020-12-04 17:05
d3 = dict(d1, **d2)

I understand that this merges the dictionary. But, is it unique? What if d1 has the same key as d2 but different value? I woul

7条回答
  •  一个人的身影
    2020-12-04 17:55

    You can use the .update() method if you don't need the original d2 any more:

    Update the dictionary with the key/value pairs from other, overwriting existing keys. Return None.

    E.g.:

    >>> d1 = {'a': 1, 'b': 2} 
    >>> d2 = {'b': 1, 'c': 3}
    >>> d2.update(d1)
    >>> d2
    {'a': 1, 'c': 3, 'b': 2}
    

    Update:

    Of course you can copy the dictionary first in order to create a new merged one. This might or might not be necessary. In case you have compound objects (objects that contain other objects, like lists or class instances) in your dictionary, copy.deepcopy should also be considered.

提交回复
热议问题