[Tutor] Combining dictionaries
Mike Cheponis
mac at Wireless.Com
Wed Sep 7 01:14:32 CEST 2005
On Tue, 6 Sep 2005, Danny Yoo wrote:
>> No, that's not what he wants.
>>
>> He wants c = a + b to work when a and b are dictionaries.
>>
>> Why is Python broken in such an obvious way?
> It might not be obvious. If a and b overlap so that they share keys, then
> we might have the following situation:
I did consider that, but of course, "update" has to deal with that issue already.
> c1 = a + b
> c2 = b + a
>
> Are c1 and c2 the same?
Answer: maybe
> One possible problem is that this kind of "merging" operation on
> dictionaries isn't "commutative". And notationally, addition is supposed
> to be so. Forcing the notation of arithmetic on dictionaries is
> seductive, but it can invite logical errors.
( See my note, below, on the "*" operator [1]. )
Then use an operator like "++" which would be non-commutative "addition".
>>> a={1:1,2:2}
>>> b={2:22,3:3}
>>> c=dict(a)
>>> c.update(b) # This would be c = a ++ b
>>> c
{1: 1, 2: 22, 3: 3}
>>> c=dict(b)
>>> c.update(a) # This would be c = b ++ a
>>> c
{1: 1, 2: 2, 3: 3}
Seems like a straightforward improvement.
--------------------------
[1] Speaking of things that are suprising:
>>> "foo" "bar "*3
'foobar foobar foobar '
>>> "foo" + "bar "*3
'foobar bar bar '
This also seems like a nasty bug (to me, at least). Because one would think that the "*"
operator would bind more closely than the '"' or implied concatenation would.
How can I actively help fix these Python bugs?
> Best of wishes to you!
Same to you!
Thanks! -Mike
More information about the Tutor
mailing list