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

Michael Selik mike at selik.org
Wed Feb 27 13:41:04 EST 2019


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.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20190227/722b277d/attachment.html>


More information about the Python-ideas mailing list