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

Greg Ewing greg.ewing at canterbury.ac.nz
Thu Feb 12 22:24:27 CET 2015


Chris Angelico wrote:
> we already know that programming isn't the same as
> mathematics.

True, but both mathematicians and programmers share a
desire to be able to reason easily and accurately about
the things they work with.

But my main objection to an asymmetrical + for dicts
is that it would be difficult to remember which way
it went.

Analogy with bytes + sequence would suggest that the
left operand wins. Analogy with dict.update would
suggest that the right operand winds.


  That's even true when we're working with numbers -
> usually because of representational limitations - but definitely so
> when analogies like "addition" are extended to other data types. But
> there are real-world parallels here. Imagine if two people
> independently build shopping lists - "this is the stuff we need" - and
> then combine them. You'd describe that as "your list and my list", or
> "your list plus my list" (but not "your list or my list"; English and
> maths tend to get "and" and "or" backward to each other in a lot of
> ways), and the resulting list would basically be set union of the
> originals. If you have room on one of them, you could go through the
> other and add all the entries that aren't already present; otherwise,
> you grab a fresh sheet of paper, and start merging the lists. (If
> you're smart, you'll group similar items together as you merge. That's
> where the analogy breaks down, though.) It makes fine sense to take
> two shopping lists and combine them into a new one, discarding any
> duplicates.
> 
> my_list = {"eggs": 1, "sugar": 1, "milk": 3, "bacon": 5}
> your_list = {"milk": 1, "eggs": 1, "sugar": 2, "coffee": 2}
> 
> (let's assume we know what units everything's in)
> 
> The "sum" of these two lists could possibly be defined as the greater
> of the two values, treating them as multisets; but if the assumption
> is that you keep track of most of what we need, and you're asking me
> if you've missed anything, then having your numbers trump mine makes
> fine sense.
> 
> I have no problem with the addition of dictionaries resulting in the
> set-union of their keys, and the values following them in whatever way
> makes the most reasonable sense. Fortunately Python actually has
> separate list and dict types, so we don't get the mess of PHP array
> merging...
> 
> ChrisA
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/



More information about the Python-ideas mailing list