[Python-ideas] Adding "+" and "+=" operators to dict

Andrew Barnert abarnert at yahoo.com
Thu Feb 12 05:58:52 CET 2015


On Feb 11, 2015, at 20:06, Greg <greg.ewing at canterbury.ac.nz> wrote:

> On 12/02/2015 4:59 p.m., Chris Angelico wrote:
>>> Addition in the usual sense of the word wouldn't be commutative for
>>> dictionaries.
>> 
>> Does it have to be? It isn't commutative for strings or tuples either.
> 
> I think associativity is the property in question, and it
> does hold for string and tuple concatenation.

No, I think commutativity is the property in question, because dict merging with the right side winning is already associative but not commutative--exactly like string and tuple addition.

Commutative means ab = ba. Associative means a(bc) = (ab)c.

Also, using addition for noncommutative operations is not some anti-mathematical perversion by Python; mathematicians (and, I believe, physicists even more so) generally use the same symbols and names for addition and multiplication of noncommutative algebras like the quaternions (and even nonassociative, like the octonions) that they use for the commutative reals and complexes. In fact, the idea of noncommutative addition or multiplication is kind of the starting point of 19th century algebra and everything that follows from it.

> Dict addition could be made associative by raising an
> exception on duplicate keys.

That would make it commutative.

> Another way would be to define {'a':x} + {'a':y} as
> {'a': x + y}, but that would probably upset a lot of
> people. :-)

Of course that's exactly what Counter does. And it also defines | to give {'a': max(x, y)}. Which is why it's important to consider the __radd__/__ror__ issue. What should happen if you add a dict to a Counter, or vice-versa?


More information about the Python-ideas mailing list