Re: Adding "+" and "+=" operators to dict 
[Posted March 4, 2015 by jake]
               
               
 
| From: |  | Donald Stufft <donald-/z0sg0XqlqBhl2p70BpVqQ-AT-public.gmane.org> | 
| To: |  | Ian Lee <ianlee1521-Re5JQEeQqe8AvxtiuMwx3w-AT-public.gmane.org> | 
| Subject: |  | Re: Adding "+" and "+=" operators to dict | 
| Date: |  | Wed, 11 Feb 2015 07:27:21 -0500 | 
| Message-ID: |  | <3A2104E9-9397-464C-BDAA-723D047956B1@stufft.io> | 
| Cc: |  | python-ideas-+ZN9ApsXKcEdnm+yROfE0A-AT-public.gmane.org | 
> On Feb 11, 2015, at 2:21 AM, Ian Lee <ianlee1521-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org> wrote:
> 
> I mentioned this on the python-dev list [1] originally as a +1 to someone else suggesting the
idea [2]. It also came up in a response to my post that I can't seem to find in the archives, so
I've quoted it below [3].
> 
> As the subject says, the idea would be to add a "+" and "+=" operator to dict that would provide
the following behavior:
> 
> >>> {'x': 1, 'y': 2} + {'z': 3}
> {'x': 1, 'y': 2, 'z': 3}
> 
> With the only potentially non obvious case I can see then is when there are duplicate keys, in
which case the syntax could just be defined that last setter wins, e.g.:
> 
> >>> {'x': 1, 'y': 2} + {'x': 3}
> {'x': 3, 'y': 2}
> 
> Which is analogous to the example:
> 
> >>> new_dict = dict1.copy()
> >>> new_dict.update(dict2)
> 
> With "+=" then essentially ending up being an alias for ``dict.update(...)``.
> 
> I'd be happy to champion this as a PEP if the feedback / public opinion heads in that direction.
> 
> 
> [1] https://mail.python.org/pipermail/python-dev/2015-February/138150.html
<https://mail.python.org/pipermail/python-dev/2015-Februar...>
> [2] https://mail.python.org/pipermail/python-dev/2015-February/138116.html
<https://mail.python.org/pipermail/python-dev/2015-Februar...>
> [3] John Wong -- 
> Well looking at just list
> a + b yields new list
> a += b yields modified a
> then there is also .extend in list. etc.  
> so do we want to follow list's footstep? I like + because + is more natural to read. Maybe this
needs to be a separate thread. I am actually amazed to remember dict + dict is not possible...
there must be a reason (performance??) for this...
> 
I’d really like this change and I think that it makes sense. The only thing I’d change is that
I think the | operator makes more sense than +. dicts are more like sets than they are like lists
so a union operator makes more sense I think.
---
Donald Stufft
PGP: 7C6B 7C5D 5E2B 6356 A926 F04F 6E3C BCE9 3372 DCFA
_______________________________________________
Python-ideas mailing list
Python-ideas-+ZN9ApsXKcEdnm+yROfE0A@public.gmane.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/