[Python-ideas] PEP: Dict addition and subtraction

Chris Angelico rosuav at gmail.com
Wed Mar 6 09:05:05 EST 2019


On Thu, Mar 7, 2019 at 12:59 AM Michael Lee <michael.lee.0x2a at gmail.com> wrote:
> If your instinct is to assume "+" means "concatenation", then it would be natural to assume that {"a": 1, "b": 2} + {"c": 3, "b": 4} would be identical to {"a": 1, "b": 2, "c": 3, "b": 4} -- literally concat the key-value pairs into a new dict.
>
> But of course, you can't have duplicate keys in Python. So, you would either recall or look up how duplicate keys are handled when constructing a dict and learn that the rule is that the right-most key wins. So the natural conclusion is that "+" would follow this existing rule -- and you end up with exactly the behavior described in the PEP.
>

Which, by the way, is also consistent with assignment:

d = {}; d["a"] = 1; d["b"] = 2; d["c"] = 3; d["b"] = 4

Rightmost one wins. It's the most logical behaviour.

ChrisA


More information about the Python-ideas mailing list