set operations on dictionaries?

Tim Chase python.list at tim.thechases.com
Mon Oct 16 14:29:41 EDT 2006


> I understand this point but this is just an argument for
> saying that it should throw an exception when the values don't
> match. It is not an argument for not doing the logical thing
> when they do. In fact in many situations it can be reasonably
> expected that the values will be the same. If not, give an
> error. There is no danger in that. The programmer should know
> whether this is a reasonable expectation in any givn case. (As
> it is at the moment, you get an error even if they match...)

Well, the operation as you describe it is easy enough to implement:

 >>> d1 = {1:42, 2:43, 3:44}
 >>> d2 = {1:42, 2:55, 5:66}
 >>> dict((k,v) for k,v in d1.items() if k in d2)
{1: 42, 2: 43}
 >>> dict((k,v) for k,v in d1.items() if k in d2 and d2[k] == v)
{1: 42}

depending on whether you want to enforce the matching of the 
values as well.

Sure, it's not a native operator, but given the ambiguity of the 
definition (do you or don't you include the values in the 
comparison?), it's best to leave it as a function rather than 
trying to shoehorn it into the __sub__ operator.

-tkc






More information about the Python-list mailing list