[Python-ideas] adding dictionaries
Steven D'Aprano
steve at pearwood.info
Sun Jul 27 03:17:39 CEST 2014
On Sun, Jul 27, 2014 at 09:34:16AM +1000, Alexander Heger wrote:
> Is there a good reason for not implementing the "+" operator for dict.update()?
[...]
> That is
>
> B += A
>
> should be equivalent to
>
> B.update(A)
You're asking the wrong question. The burden is not on people to justify
*not* adding new features, the burden is on somebody to justify adding
them. Is there a good reason for implementing the + operator as
dict.update? We can already write B.update(A), under what circumstances
would you spell it B += A instead, and why?
> It would be even better if there was also a regular "addition"
> operator that is equivalent to creating a shallow copy and then
> calling update():
>
> C = A + B
>
> should equal to
>
> C = dict(A)
> C.update(B)
That would be spelled C = dict(A, **B).
I'd be more inclined to enhance the dict constructor and update methods
so you can provide multiple arguments:
dict(A, B, C, D) # Rather than A + B + C + D
D.update(A, B, C) # Rather than D += A + B + C
> My apologies if this has been posted before but with a quick google
> search I could not see it; if it was, could you please point me to the
> thread? I assume this must be a design decision that has been made a
> long time ago, but it is not obvious to me why.
I'm not sure it's so much a deliberate decision not to implement
dictionary addition, as uncertainty as to what dictionary addition ought
to mean. Given two dicts:
A = {'a': 1, 'b': 1}
B = {'a': 2, 'c': 2}
I can think of at least four things that C = A + B could do:
# add values, defaulting to 0 for missing keys
C = {'a': 3, 'b': 1, 'c': 2}
# add values, raising KeyError if there are missing keys
# shallow copy of A, update with B
C = {'a': 2, 'b': 1, 'c': 2}
# shallow copy of A, insert keys from B only if not already in A
C = {'a': 1, 'b': 1, 'c': 2}
Except for the second one, I've come across people suggesting that each
of the other three is the one and only obvious thing for A+B to do.
--
Steven
More information about the Python-ideas
mailing list