[Python-ideas] dict '+' operator and slicing support for pop

George Sakkis george.sakkis at gmail.com
Tue Mar 17 17:03:16 CET 2009

On Tue, Mar 17, 2009 at 11:00 AM, Andrii V. Mishkovskyi
<mishok13 at gmail.com> wrote:

> 1. Add ability to use '+' operator for dicts
> I often wonder why list and tuple instances have '+' and '+='
> operators but dicts don't?
> It's not that rare in my code (and code written by others, as it
> seems) that i have to write:
> a.update(b)
> return a
> I do understand that adding additional magic method may be
> inappropriate for dict, but I think it would be nice addition to a
> language. So, my proposal is that:
> x = a + b
> would become equivalent to
> x = dict(a, **b)
> a += b
> would become equivalent to
> a.update(b)

That's one way to define dict addition but it's not the only, or even,
the best one. It's hard to put in words exactly why but I expect "a+b"
to take into account the full state of the operands, not just a part
of it. In your proposal the values of the first dict for the common
keys are effectively ignored, which doesn't seem to me as a good fit
for an additive operation. I would find at least as reasonable and
intuitive the following definition that doesn't leak information:

def sum_dicts(*dicts):
    from collections import defaultdict
    s = defaultdict(list)
    for d in dicts:
        for k,v in d.iteritems():
    return s

>>> d1 = {'a':2,'b':5}
>>> d2 = {'a':2,'c':6,'z':3}
>>> d3 = {'b':2,'c':5}
>>> sum_dicts(d1,d2,d3)
defaultdict(<type 'list'>, {'a': [2, 2], 'c': [6, 5], 'b': [5, 2], 'z': [3]})


More information about the Python-ideas mailing list