[Python-ideas] adding dictionaries

Alexander Heger python at 2sn.net
Sun Jul 27 01:34:16 CEST 2014


Is there a good reason for not implementing the "+" operator for dict.update()?

A = dict(a=1, b=1)
B = dict(a=2, c=2)
B += A
B
dict(a=1, b=1, c=2)

That is

B += A

should be equivalent to

B.update(A)

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)

(obviously not the same as C = B + A, but the "+" operator is not
commutative for most operations)

class NewDict(dict):
    def __add__(self, other):
         x = dict(self)
         x.update(other)
         return x
    def __iadd__(self, other):
         self.update(other)


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.


More information about the Python-ideas mailing list