[melbourne-pug] Why can't two dicts be added together?

Sam Lai samuel.lai at gmail.com
Thu Oct 17 03:47:26 CEST 2013


@Javier, ah, those were the search terms I was looking for.

I understand there's potential ambiguity, but it seems appropriate
that there is an accepted convention (where personally, the + is
equivalent to .update on a new dict in the order presented). Those
examples where a list is created for clashing dict keys feel like
they're doing a lot more than what a dict should do. In any case, the
performance issues associated with creating a new dict each time
probably wouldn't be too good anyway.

Thanks everyone!

On 17 October 2013 12:10, Tobias Sargeant <tobias.sargeant at gmail.com> wrote:
> Set union (| operator) is commutative.
>
>>>> {2,3} | {1,2} == {1,2} | {2,3}
> True
>
> List concatenation isn't
>
>>>> [2,3] + [1,2] == [1,2] + [2,3]
> False
>
> so maybe the expectation of commutativity for + isn't a good argument (or is an argument that list concatenation should be called something else :) ).
>
> If you want a (verbose) one-liner for "concatenation" of dictionaries, there's always:
>
> dict(itertools.chain({1:1}.iteritems(), {2:2}.iteritems()))
>
> On 17/10/2013, at 11:31 AM, Sam Lai <samuel.lai at gmail.com> wrote:
>
>> It's almost Friday, so I have a question where I'm pretty sure I'm
>> missing something obvious.
>>
>> Given,
>>
>> d1 = { 'a' : 'b' }
>> d2 = { 'c' : 'd' }
>>
>> ...  why isn't d3 = d1 + d2 implemented to be equivalent to -
>>
>> d3 = { }
>> d3.update(d1)
>> d3.update(d2)
>>
>> It doesn't work for sets either, but it works in this fashion for
>> lists. Is this because the operation is non-commutative for sets and
>> dicts and may result in a loss of data when clashing keys are
>> involved? Isn't that implicit when working with sets and dicts?
>>
>> Sam
>> _______________________________________________
>> melbourne-pug mailing list
>> melbourne-pug at python.org
>> https://mail.python.org/mailman/listinfo/melbourne-pug
>
> _______________________________________________
> melbourne-pug mailing list
> melbourne-pug at python.org
> https://mail.python.org/mailman/listinfo/melbourne-pug


More information about the melbourne-pug mailing list