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

Donald Stufft donald at stufft.io
Thu Feb 12 19:12:26 CET 2015


> On Feb 12, 2015, at 1:00 PM, Mark Young <marky1991 at gmail.com> wrote:
> 
> Sure, it's something that people want to do. But then the question becomes "How do you want to merge them?" and then the answers to that are all over the board, to the point that there's no one obvious way to do it.

Honestly I don’t really think it is all that over the board. Basically in every method of merging that plain dictionaries currently offer it’s a “last use of the key wins”. The only place this isn’t the case is specialized dictionary like classes like Counter. I think using anything other than “last use of the key wins” would be inconsistent with the rest of Python and I think it’s honestly the only thing that can work generically too.

See:

>>> 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/20150212/02f73193/attachment.sig>


More information about the Python-ideas mailing list