[Python-ideas] Adding "+" and "+=" operators to dict
Chris Angelico
rosuav at gmail.com
Thu Feb 12 16:46:45 CET 2015
On Fri, Feb 13, 2015 at 2:21 AM, Skip Montanaro
<skip.montanaro at gmail.com> wrote:
> On Wed, Feb 11, 2015 at 9:59 PM, Chris Angelico <rosuav at gmail.com> wrote:
>> Does it have to be? It isn't commutative for strings or tuples either.
>
> Good point. I never think of string "addition" as anything other than
> concatenation. I guess the same would be true of dictionaries. Still,
> if I add two strings, lists or tuples, the len() of the result is the
> same as the sum of the len()s. That wouldn't necessarily be the case
> for dictionaries, which, though well-defined, still can leave you open
> for a bit of a surprise when the keys overlap.
Yes, but we already know that programming isn't the same as
mathematics. 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
More information about the Python-ideas
mailing list