[Python-ideas] Dict joining using + and +=
Stefan Behnel
stefan_ml at behnel.de
Fri Mar 1 10:03:13 EST 2019
Rémi Lapeyre schrieb am 01.03.19 um 15:50:
> Le 1 mars 2019 à 15:41:52, Stefan Behnel a écrit:
>
>> 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+).
>
> Thanks Stefan for your feedback, unless I’m mistaken this does not work like
> Rhodri suggested, he said:
>
> I can tell it's pretty straightforward:
>
> d = d1 + d2 is equivalent to:
>
> >>> d = d1.copy()
> >>> d.update(d2)
>
> But doing this:
>
> >>> d1 = OrderedDict({"a": 1, "b": 2, "c": 3})
> >>> d2 = OrderedDict({"d": 4, "b": 5})
> >>> d = d1.copy()
> >>> d.update(d2)
> >>> d
> OrderedDict([('a', 1), ('b', 5), ('c', 3), ('d', 4)])
>
> It looks like that the semantics are either not straightforward or what you
> proposed is not the only reasonable answer. Am I missing something?
No, I was, apparently. In Py3.7:
>>> d1 = {"a": 1, "b": 2, "c": 3}
>>> d1
{'a': 1, 'b': 2, 'c': 3}
>>> d2 = {"d": 4, "b": 5}
>>> d = d1.copy()
>>> d.update(d2)
>>> d
{'a': 1, 'b': 5, 'c': 3, 'd': 4}
I think the behaviour makes sense when you know how it's implemented (keys
are stored separately from values). I would have been less surprised if the
keys had also been reordered, but well, this is how it is now in Py3.6+, so
this is how it's going to work also for the operator.
No *additional* surprises here. ;)
Stefan
More information about the Python-ideas
mailing list