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

Stefan Behnel stefan_ml at behnel.de
Fri Mar 1 09:40:25 EST 2019

Rémi Lapeyre schrieb am 01.03.19 um 15:06:
> I’m having issues to understand the semantics of d1 + d2.
> I think mappings are more complicated than sequences it some things
> seems not obvious to me.
> What would be OrderedDict1 + OrderedDict2, in which positions would be
> the resulting keys, which value would be used if the same key is
> present in both?

The only reasonable answer I can come up with is:

1) unique keys from OrderedDict1 are in the same order as before
2) duplicate keys and new keys from OrderedDict2 come after the keys from
d1, in their original order in d2 since they replace keys in d1.

Basically, the expression says: "take a copy of d1 and add the items from
d2 to it". That's exactly what you should get, whether the mappings are
ordered or not (and dict are ordered by insertion in Py3.6+).

> What would be defaultdict1 + defaultdict2?

No surprises here, the result is a copy of defaultdict1 (using the same
missing-key function) with all items from defaultdict2 added.

Remember that the order of the two operands matters. The first always
defines the type of the result, the second is only added to it.

> It seems to me that subclasses of dict are complex mappings for which
> « merging » may be less obvious than for sequences.

It's the same for subclasses of sequences.


More information about the Python-ideas mailing list