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

Guido van Rossum guido at python.org
Wed Feb 27 13:48:21 EST 2019


On Wed, Feb 27, 2019 at 10:42 AM Michael Selik <mike at selik.org> wrote:

>
>
> On Wed, Feb 27, 2019 at 10:22 AM Anders Hovmöller <boxed at killingar.net>
> wrote:
>
>> I dislike the asymmetry with sets:
>>
>> > {1} | {2}
>> {1, 2}
>>
>> To me it makes sense that if + works for dict then it should for set too.
>>
>> / Anders
>>
>> > On 27 Feb 2019, at 17:25, João Matos <jcrmatos at gmail.com> wrote:
>> >
>> > Hello,
>> >
>> > I would like to propose that instead of using this (applies to Py3.5
>> and upwards)
>> > dict_a = {**dict_a, **dict_b}
>> >
>> > we could use
>> > dict_a = dict_a + dict_b
>>
>
>
> The dict subclass collections.Counter overrides the update method for
> adding values instead of overwriting values.
>
>
> https://docs.python.org/3/library/collections.html#collections.Counter.update
>
> Counter also uses +/__add__ for a similar behavior.
>
>     >>> c = Counter(a=3, b=1)
>     >>> d = Counter(a=1, b=2)
>     >>> c + d # add two counters together:  c[x] + d[x]
>     Counter({'a': 4, 'b': 3})
>
> At first I worried that changing base dict would cause confusion for the
> subclass, but Counter seems to share the idea that update and + are
> synonyms.
>

Great, this sounds like a good argument for + over |. The other argument is
that | for sets *is* symmetrical, while + is used for other collections
where it's not symmetrical. So it sounds like + is a winner here.

-- 
--Guido van Rossum (python.org/~guido)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20190227/8def7fdc/attachment.html>


More information about the Python-ideas mailing list