[Python-ideas] Dict joining using + and +=

Steven D'Aprano steve at pearwood.info
Wed Feb 27 18:46:39 EST 2019


On Wed, Feb 27, 2019 at 10:34:43AM -0700, George Castillo wrote:
> >
> > The key conundrum that needs to be solved is what to do for `d1 + d2` when
> > there are overlapping keys. I propose to make d2 win in this case, which is
> > what happens in `d1.update(d2)` anyways. If you want it the other way,
> > simply write `d2 + d1`.
> 
> 
> This would mean that addition, at least in this particular instance, is not
> a commutative operation.  Are there other places in Python where this is
> the case?

Strings, bytes, lists, tuples.

In this case, I wouldn't call it dict addition, I would call it a union 
operator. That suggests that maybe we match sets and use | for union.

That also suggests d1 & d2 for the intersection between two dicts, but 
which value should win?

More useful than intersection is, I think, dict subtraction: d1 - d2 
being a new dict with the keys/values from d1 which aren't in d2.



-- 
Steven


More information about the Python-ideas mailing list