[Python-ideas] PEP: Dict addition and subtraction

James Lu jamtlu at gmail.com
Mon Mar 4 10:09:32 EST 2019


>> On Mar 4, 2019, at 4:51 AM, Stefan Behnel <stefan_ml at behnel.de> wrote:
> 
> Jimmy Girardet schrieb am 04.03.19 um 10:12:
>> I'm not old on this list but every time there is a proposal, the answer
>> is "what are you trying to solve ?".
>> 
>> Since
>> 
>> |z ={**x,**y} and z.update(y) Exists, I can"t find the answer.
> 
> I think the main intentions is to close a gap in the language.
> 
>    [1,2,3] + [4,5,6]
> 
> works for lists and tuples,
> 
>    {1,2,3} | {4,5,6}
> 
> works for sets, but joining two dicts isn't simply
> 
>    {1:2, 3:4} + {5:6}
> 
> but requires either some obscure syntax or a statement instead of a simple
> expression.
> 
> The proposal is to enable the obvious syntax for something that should be
> obvious.

Rebutting my “throw KeyError on conflicting keys for +” proposal:
Indeed but + is never destructive in those contexts: duplicate list items are okay because they’re ordered, duplicated set items are okay because they mean the same thing (when two sets contain the same item and you merge the two the “containing” means the same thing), but duplicate dict keys mean different things. 

How many situations would you need to make a copy of a dictionary and then update that copy and override old keys from a new dictionary?

It’s better to have two different syntaxes for different situations. 

The KeyError of my proposal is a feature, a sign that something is wrong, a sign an invariant is being violated. Yes, {**, **} syntax looks abnormal and ugly. That’s part of the point– how many times have you needed to create a copy of a dictionary and update that dictionary with overriding keys from a new dictionary? It’s much more common to have non-conflicting keys. The ugliness of the syntax makes one pause and think and ask: “Why is it important that the keys from this dictionary override the ones from another dictionary?”

PROPOSAL EDIT: I think KeyError should only be thrown if the same keys from two dictionaries have values that are not __eq__.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20190304/882bbc53/attachment.html>


More information about the Python-ideas mailing list