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

Steven D'Aprano steve at pearwood.info
Fri Feb 13 07:30:03 CET 2015


On Fri, Feb 13, 2015 at 01:40:48PM +0900, Stephen J. Turnbull wrote:
> Donald Stufft writes:

[...]
>  > however being able to
>  > type that as new_dict = dict1 + dict2 is more succinct, cleaner,
>  > and just a little bit nicer.
> 
> Yes, no, and no.
> 
> Succint?  Yes.  Just count characters or lines (but both are
> deprecated practices in juding Python style).
> 
> Cleaner?  No.  The syntax is cleaner (way fewer explicit operations),
> but the semantics are muddier for me.  At one time or another, at
> least four different interpretations of "dict addition" have been
> proposed already:
> 
> 1.  item of left operand wins
>     Ie, "add new keys and their values".
>     This is the one I think of as "add", and it's most analogous to
>     the obvious algorithm for "add-as-in-union" for sets.
> 
> 2.  item of right operand wins
>     Ie, "add new values, inserting new keys as needed".
>     I think of this as "update", its per-item semantics is "replace",
>     but it seems to be the favorite for getting "+" syntax.  Eh?
> 
> 3.  keywise addition
>     This is collections.Counter, although there are several plausible
>     treatments of missing values (error, additive identity).
> 
> 4.  keys duplication is an error
>     Strictly speaking nobody has proposed this, but it is implicit in
>     many of the posts that give an example of adding dictionaries with
>     no duplicate keys and say, "it's obvious what d1 + d2 should be".
>     Then there's the variant where duplicate keys with the same value
>     is OK.

Actually, there have been a few posts where people have suggested that 
duplicated keys should raise an exception. Including one that suggested 
it would be good for novices but bad for experienced coders.


> And in the "adding shopping dicts" example you could plausibly argue
> for two more:
> 
> 5.  keywise max of values
>     So the first person to the refrigerator always has enough eggs to
>     bake her cake, even if nobody else does.

That's the multiset model.

> 6.  keywise min of values
>     If you are walking to the store.

One more, which was suggested on Stackoverflow:

{'spam': 2, 'eggs': 1} + {'ham': 1, 'eggs': 3}
=> {'ham': 1, 'spam': 2, 'eggs': (1, 3)}



-- 
Steve


More information about the Python-ideas mailing list