I am a new Python user and I would have some doubts.
I know I that the +
operator not only performs sum between numbers but also concatenation between strings or lists. Why this is not allowed for dictionaries?
I am a new Python user and I would have some doubts.
I know I that the +
operator not only performs sum between numbers but also concatenation between strings or lists. Why this is not allowed for dictionaries?
How would the +
operator for dicts handle duplicate keys? e.g.
>>> {'d': 2} + {'d': 1}
Perhaps like a Counter
?
>>> from collections import Counter
>>> Counter({'d': 2}) + Counter({'d': 1})
Counter({'d': 3})
Or like a defaultdict
?
{'d': [2, 1]}
Or overwriting the 1st key like dict.update
?
>>> d = {'d': 2}
>>> d.update({'d':1})
>>> d
{'d': 1}
Or leaving only the 1st key?
{'d': 2}
It's frankly ambiguous!
See also PEP 0584:
Use The Addition Operator
This PEP originally started life as a proposal for dict addition, using the + and += operator. That choice proved to be exceedingly controversial, with many people having serious objections to the choice of operator. For details, see previous versions of the PEP and the mailing list discussions.
Note Guido himself did consider and discuss this; see also issue36144.
There's an accepted PEP for this, coming in Python 3.9 :)
https://www.python.org/dev/peps/pep-0584/#specification
d = {'spam': 1, 'eggs': 2, 'cheese': 3}
e = {'cheese': 'cheddar', 'aardvark': 'Ethel'}
d | e {'spam': 1, 'eggs': 2, 'cheese': 'cheddar', 'aardvark': 'Ethel'}
e | d {'aardvark': 'Ethel', 'spam': 1, 'eggs': 2, 'cheese': 3}