Search code examples
python-3.xdictionarymergekey-valueoverwrite

Merge dictionaries to overwrite duplicate keys without overwriting duplicate and non-duplicate values


Input:

dict1 = {a: [xxx, zzz]}
dict2 = {a: [yyy, zzz]}

Desired output:

dict3 = {a: [xxx, zzz, yyy, zzz]}

I have tried:

dict3 = dict1 | dict2

and

dict3 = dict1.copy()
d3 |= d2

However, the merge | and update |= operators overwrites with the last seen dict as precedence, resulting in:

dict3 = {a: [yyy, zzz]}

Solution

  • This is the desired result, as stated in the PEP 584,

    Dict union will return a new dict consisting of the left operand merged with the right operand, each of which must be a dict (or an instance of a dict subclass). If a key appears in both operands, the last-seen value (i.e. that from the right-hand operand) wins

    You may need to merge two dict by hands:

    In [8]: dict1 = {'a': ['xxx', 'zzz']}
       ...: dict2 = {'a': ['yyy', 'zzz']}
       ...: for k, v in dict2.items():
       ...:     if k in dict1:
       ...:         dict1[k] += v
       ...:
    
    In [9]: print(dict1)
    {'a': ['xxx', 'zzz', 'yyy', 'zzz']}