Search code examples
pythondictionarypython-internals

Why is arithmetic not supported for dict? Usupported operand type(s) for +: 'dict' and 'dict'


In Python, there is a possibility to sum lists and tuples, e.g.

>>> print([1, 2] + [4, 5]) 
>>> [1, 2, 4, 5]

>>> print((1, 2) + (4, 5))
>>> (1, 2, 3, 4)

But trying to do the same with dicts will raise:

TypeError: unsupported operand type(s) for +: 'dict' and 'dict'

I guess there could be the same behavior as update() has for cases when merging two dicts with the same key:

>>> foo = {'a': 10, 'b': 20}
>>> bar = {'a': 20}
>>> foo.update(bar)
>>> print(foo)
>>> {'a': 20, 'b': 20}

Why these operands aren't implemented? Any optimization issues or just by design?


Solution

  • In Python 3.9 was added dict union operator, for example:

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

    Also, take a look at motivation, it has a good overview of why this was included in the language.