[Python-ideas] adding dictionaries

Andrew Barnert abarnert at yahoo.com
Tue Jul 29 00:17:22 CEST 2014


On Jul 28, 2014, at 13:59, Alexander Heger <python at 2sn.net> wrote:

> On 29 July 2014 02:08, Guido van Rossum <guido at python.org> wrote:
>> In addition, dict(A, **B) is not something you easily stumble upon when your
>> goal is "merge two dicts"; nor is it even clear that that's what it is when
>> you read it for the first time.
>> 
>> All signs of too-clever hacks in my book.
> 
> I try to convince students to learn and *use* python.
> 
> If I tell students to merge 2 dictionaries they have to do dict(A,
> **B} or {**A, **B} that seem less clear (not something you "stumble
> across" as Guidon says) than A + B; then we still have to tell them
> the rules of the operation, as usual for any operation.
> 
> It does not have to be "+", could be the "union" operator "|" that is
> used for sets where
> s.update(t)
> is the same as
> s |= t

The difference is that with sets, it (at least conceptually) doesn't matter whether you keep elements from s or t when they collide, because by definition they only collide if they're equal, but with dicts, it very much matters whether you keep items from s or t when their keys collide, because the corresponding values are generally _not_ equal. So this is a false analogy; the same problem raised in the first three replies on this thread still needs to be answered: Is it obvious that the values from b should overwrite the values from a (assuming that's the rule you're suggesting, since you didn't specify; translate to the appropriate question if you want a different rule) in all real-life use cases? If not, is this so useful that the benefits in some uses outweigh the almost certain confusion in others? Without a compelling "yes" to one of those two questions, we're still at square one here; switching from + to | and making an analogy with sets doesn't help.

> ... and accordingly
> 
> D = A | B | C
> 
> Maybe this operator is better as this equivalence is already being
> used (for sets).  Accordingly "union(A,B)" could do a merge operation
> and return the new dict().

Wouldn't you expect a top-level union function to take any two iterables and return the union of them as a set (especially given that set.union accepts any iterable for its non-self argument)? A.union(B) seems a lot better than union(A, B).

Then again, A.updated(B) or updated?A, B) might be even better, as someone suggested, because the parallel between update and updated (and between e.g. sort and sorted) is not at all problematic.

> (this then still allows people who want "+" to add the values be made
> happy in the long run)
> 
> -Alexander
> _______________________________________________
> 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