dictionary

Alex Martelli aleax at aleax.it
Fri May 3 04:14:23 EDT 2002


Ante Bagaric wrote:

> hmmm is there a reason why operators + and - don't work with dictionaries?
> Couldn't + be like union and - like difference?
> I guess this question was brough up dozens of times thou.. so forgive me

I don't recall seeing it often asked, no.  If I had to hazard a guess at
the reasons, I'd say it's because there's no single, natural, obvious way
of defining these operations.  Dicts aren't just the set of their keys --
each key has a corresponding value.  What happens when a key is in both
dicts with different values -- how does that 'count'?  For "addition", a
dict has an .update method where the RHS' associations dominate (alas, not
a .merge method where self's associations dominate).  Difference looks
harder.  What's {1:2,3:4}-{1:5}, for example?

There's another way to look at this.  Can the operations you have in mind
be expressed in terms of mappings' current public interface?  If so, then
making them into mappings' methods only makes sense if a strong performance
boost can be obtained by exploiting private implementation details (as I
think is the case for .update).  Otherwise, you're making life harder for
any implementer of mappings (there's more stuff he or she must implement)
and might rather want to write the things as public functions that just
call said public interface.


Alex




More information about the Python-list mailing list