[Python-ideas] Adding "+" and "+=" operators to dict

Donald Stufft donald at stufft.io
Sat Feb 14 07:17:15 CET 2015


> On Feb 14, 2015, at 1:09 AM, Stephen J. Turnbull <stephen at xemacs.org> wrote:
> 
> Chris Barker writes:
> 
>> merging two dicts certainly is _something_ like addition.
> 
> But you can't say what that something is with precision, even if you
> abstract, and nobody contests that different applications of dicts
> have naively *different*, and in implementation incompatible,
> "somethings".
> 
> So AFAICS you have to fall back on "my editor forces me to type all
> the characters, so let's choose the interpretation I use most often
> so cI can save some typing without suffering too much cognitive
> dissonance.”
> 

Or we can choose the interpretation that has already been chosen by
multiple locations within Python. That keys are replaced and rhs
wins. This is consistent with basically every location in the stdlib
and Python core where two dicts get combined in some fashion other than
specialized subclasses.


    >>> a = {1: True, 2: True}
    >>> b = {2: False, 3: False}
    >>> dict(list(a.items()) + list(b.items()))
    {1: True, 2: False, 3: False}

    And

    >>> a = {1: True, 2: True}
    >>> b = {2: False, 3: False}
    >>> c = a.copy()
    >>> c.update(b)
    >>> c
    {1: True, 2: False, 3: False}

    And

    >>> {1: True, 2: True, 2: False, 3: False}
    >>> {1: True, 2: False, 3: False}

    And

    >>> a = {"a": True, "b": True}
    >>> b = {"b": False, "c": False}
    >>> dict(a, **b)
    {'b': False, 'c': False, 'a': True}


---
Donald Stufft
PGP: 7C6B 7C5D 5E2B 6356 A926 F04F 6E3C BCE9 3372 DCFA

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 801 bytes
Desc: Message signed with OpenPGP using GPGMail
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20150214/c244e80e/attachment.sig>


More information about the Python-ideas mailing list