pythondictionarymerge

How do I merge two dictionaries in a single expression in Python?


I want to merge two dictionaries into a new dictionary.

x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
z = merge(x, y)

>>> z
{'a': 1, 'b': 3, 'c': 4}

Whenever a key k is present in both dictionaries, only the value y[k] should be kept.


Solution

  • Python 3.9+ only

    Merge (|) and update (|=) operators have been added to the built-in dict class.

    >>> d = {'spam': 1, 'eggs': 2, 'cheese': 3}
    >>> e = {'cheese': 'cheddar', 'aardvark': 'Ethel'}
    >>> d | e
    {'spam': 1, 'eggs': 2, 'cheese': 'cheddar', 'aardvark': 'Ethel'}
    

    The augmented assignment version operates in-place:

    >>> d |= e
    >>> d
    {'spam': 1, 'eggs': 2, 'cheese': 'cheddar', 'aardvark': 'Ethel'}
    

    See PEP 584