Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't Python dictionaries support '+' operator

I've been musing as to why the Python language's standard dict class doesn't support addition/subtraction operators such as '+' or '+=', e.g.

>>> foo = {'a': 1, 'b': 2}
>>> bar = {'c': 3, 'd': 4}

>>> foo + bar
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'dict' and 'dict'

My wishful thinking would be for the following result instead:

>>> foo + bar 
{'a': 1, 'b': 2, 'c': 3, 'd': 4}

Equally why doesn't __radd__(self, other) result in the same as self.__update__(other)?

>>> foo += bar
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +=: 'dict' and 'dict'    

Does anyone know the historic reasons for the default behaviour?

(I concede that it could be ambiguous which value should be used in scenarios where foo and bar have the same key but different key values)

like image 589
Liam Deacon Avatar asked Oct 14 '25 18:10

Liam Deacon


1 Answers

Does anyone know the historic reasons for the default behaviour?

Guido van Rossum commented that he liked update() better and thinks a + operator wouldn't read clearly in code.

FWIW, he did approve PEP 448 which gives your another way to do it using star-unpacking generalizations:

>>> a = {'a': 1, 'b': 2}
>>> b = {'c': 3, 'b': 4}
>>> {**a, **b}
{'a': 1, 'b': 4, 'c': 3}

There are several reasons why + might not be a good idea. Usually, we expect addition to be commutative, but dict addition would fail whenever there were overlapping keys with distinct values. The "normal" use case is to update only dict in-place, but the usual semantics of + would copy the contents of both inputs to create a new dict (which is somewhat wasteful).

In addition, Python has collections.ChainMap which replaces the expense of copying with a new expense of potentially having multiple lookups.

like image 200
Raymond Hettinger Avatar answered Oct 17 '25 06:10

Raymond Hettinger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!