Re: Adding dictionaries

Guido.van.Rossum@cwi.nl
Fri, 05 Aug 1994 20:45:16 +0200

Lance Ellinghouse:
> >> What I would like to see is:
> >> >>> a+b
> >> {'test': 1, 'test2': 3}
> >>
> >> if a and b both had the same keys, then I think b should override the
> >> keys in a.
> >> You could also do subtraction of key-value pairs.

George Reynolds:
> I like the concept, but I get uncomfortable when the 'standard' semantics
> of an operand is changed. In this case '+' is thought of as being
> commutative. However the semantics you propose is not. How'bout
>
> >>> a.add(b)
>
> or other variations with different semantics.

Actually, + is also used for sequence concatenation, and 'tk'+'python'
is quite different from 'python'+'tk'...

My own worries are more about things like

a = {'perl': 4, 'python': 1} + {'perl': 5, 'python': 1}

Should a['perl'] be 4 or 5? Or should the addition raise an error?

In any case, I suspect that in most cases where there's a real need
for something like this, the need is for a.merge(b) with the following
semantics:

for k in b.keys(): a[k] = b[k]

(I.e. modify a in place rather than creating a new dictionary object.)

Given that this can already be written quite concisely, I don't know
that there is a real need for a built-in operator or method to
accomplish this. (This question has popped up at least twice in the
last 4 weeks -- maybe there is a real need? Or are posters
influencing each other subconsciously?)

Subtraction could be defined in a similar manner, and I see even less
use for that.

--Guido van Rossum, CWI, Amsterdam <Guido.van.Rossum@cwi.nl>
<URL:http://www.cwi.nl/cwi/people/Guido.van.Rossum.html>