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

Josiah Carlson josiah.carlson at gmail.com
Tue Mar 17 18:36:19 CET 2009


On Tue, Mar 17, 2009 at 9:03 AM, George Sakkis <george.sakkis at gmail.com> wrote:
> 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():
>            s[k].append(v)
>    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]})

Both of the ideas suffer from "+ is no longer commutative", which
sort-of bothers me.  I say sort-of, because I would actually prefer
Andrii's semantics over yours, and if you prefer the elements from b,
you use 'a + b', but if you prefer the elements from a, you use 'b +
a'.  Then again, I'm tending towards a -.75 on the entire idea;
despite it being convenient, I can see non-comutativity as being
confusing.

As for the list slice popping...I'm tending towards a -1.  While I can
see the convenience in some cases, I'm just not sure it's compelling
enough (especially because you need to generate the slice in advance
of using it).

As stated in the past...not all 2 line functions need to be built-in
or syntax.  I don't believe either of these are able to pass the "is
it necessary as part of a compelling use-case?" question.

 - Josiah



More information about the Python-ideas mailing list