In Python, there is a possibility to sum lists and tuples, e.g.
JavaScript
x
6
1
>>> print([1, 2] + [4, 5])
2
>>> [1, 2, 4, 5]
3
4
>>> print((1, 2) + (4, 5))
5
>>> (1, 2, 3, 4)
6
But trying to do the same with dicts will raise:
JavaScript
1
2
1
TypeError: unsupported operand type(s) for +: 'dict' and 'dict'
2
I guess there could be the same behavior as update()
has for cases when merging two dicts with the same key:
JavaScript
1
6
1
>>> foo = {'a': 10, 'b': 20}
2
>>> bar = {'a': 20}
3
>>> foo.update(bar)
4
>>> print(foo)
5
>>> {'a': 20, 'b': 20}
6
Why these operands aren’t implemented? Any optimization issues or just by design?
Advertisement
Answer
In Python 3.9 was added dict union operator, for example:
JavaScript
1
7
1
>>> d = {'spam': 1, 'eggs': 2, 'cheese': 3}
2
>>> e = {'cheese': 'cheddar', 'aardvark': 'Ethel'}
3
>>> d | e
4
{'spam': 1, 'eggs': 2, 'cheese': 'cheddar', 'aardvark': 'Ethel'}
5
>>> e | d
6
{'cheese': 3, 'aardvark': 'Ethel', 'spam': 1, 'eggs': 2}
7
Also, take a look at motivation, it has a good overview of why this was included in the language.