# [Python-ideas] Dict joining using + and +=

Steven D'Aprano steve at pearwood.info
Fri Mar 1 08:09:50 EST 2019

```On Fri, Mar 01, 2019 at 08:59:45PM +0900, INADA Naoki wrote:
>
> str is not commutative, but it satisfies a in (a+b), and b in (a+b).
> There are no loss.

Is this an invariant you expect to apply for other classes that support

5 in (5 + 6)

[1, 2, 3] in ([1, 2, 3] + [4, 5, 6])

Since it doesn't apply for int, float, complex, list or tuple, why do
you think it must apply to dicts?

> In case of dict + dict, it not only sum.  There may be loss value.

Yes? Why is that a problem?

>    {"a":1} + {"a":2} = ?

Would you like to argue that Counter.__add__ is a mistake for the same
reason?

Counter(('a', 1)) + Counter(('a', 2)) = ?

For the record, what I expected the above to do turned out to be
*completely wrong* when I tried it. I expected Counter({'a': 3}) but the
actual results are Counter({'a': 2, 1: 1, 2: 1}).

Every operation is going to be mysterious if you have never
learned what it does:

from array import array
a = array('i', [1, 2, 3])
b = array('i', [10, 20, 30])
a + b = ?

Without trying it or reading the docs, should that be an
error, or concatenation, or element-wise addition?

> In case of a.update(b), it's clear that b wins.

It wasn't clear to me when I was a beginner and first came across
dict.update. I had to learn what it did by experimenting with manual
loops until it made sense to me.

> In case of a + b, "which wins" or "exception raised on duplicated key?" is
> unclear to me.

Many things are unclear to me too. That doesn't make them any less
useful.

--
Steven
```