1

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?

Chris_Rands
  • 38,994
  • 14
  • 83
  • 119
  • 1
    It *could* be defined maybe, even if it's not obvious what this definition would be, but the actual answer is "because the designers of the Python language decided to not define the + operator for dictionaries". – mkrieger1 Jun 04 '20 at 08:29
  • You will find your answer here: https://stackoverflow.com/questions/38987/how-do-i-merge-two-dictionaries-in-a-single-expression-in-python/26853961#26853961 – Marcel Jun 04 '20 at 08:32

2 Answers2

3

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.

Chris_Rands
  • 38,994
  • 14
  • 83
  • 119
  • Adding to this: the nearest equivalent would be `dict.update`, but note that the name is explicitly *update*, suggesting that values will be replaced, which `+` doesn't suggest… – deceze Jun 04 '20 at 08:29
2

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}

ACimander
  • 1,852
  • 13
  • 17