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

Ben Finney ben+python at benfinney.id.au
Thu Oct 17 02:54:29 CEST 2013


Sam Lai <samuel.lai at gmail.com> writes:

> 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)

Given::

    d1 = {'a': "spam", 'b': "eggs"}
    d2 = {'b': "beans", 'c': "ham"}

What should this do::

    d3 = d1 + d2

Since the correct behaviour is ambiguous, Python refuses the temptation
to guess. If you want to have a particular behaviour, you need to be
explicit as in your example.

> It doesn't work for sets either, but it works in this fashion for
> lists.

Not “in this fashion”; it appends the sequences.

There is no defined order for dicts nor sets, and they have a uniqueness
guarantee which lists do not have.

So appending lists is an unambiguously correct behaviour for ‘+’ for two
lists, whereas the same is not true for dicts and sets.

-- 
 \            “Beware of bugs in the above code; I have only proved it |
  `\                 correct, not tried it.” —Donald Knuth, 1977-03-29 |
_o__)                                                                  |
Ben Finney



More information about the melbourne-pug mailing list