I want a dictionary class that implements an intersection_update method, similar in spirit to dict.update but restricting the updates only to those keys that are already present in the calling instance (see below for some example implementations).
But, in the spirit of Wheel Reinvention Avoidance, before I go off implementing (and writing tests for, etc.) a mapping class with this additional functionality, does anything like this already exist in a more-or-less standard module?
To be clear, the intersection_update method I have in mind would do something like this:
def intersection_update(self, other):
for k in self.viewkeys() & other.viewkeys():
self[k] = other[k]
…although an actual implementation may attempt some possible optimizations, like, e.g.:
def intersection_update(self, other):
x, y = (self, other) if len(self) < len(other) else (other, self)
for k in x.iterkeys():
if k in y:
self[k] = other[k]
Edit: In the original version of this post I had written “Alternatively, is there a standard Python idiom that obviates the need to implement a [class with a intersection_update] method?”, but I deleted almost immediately it because, upon further reflection, I realized that was an invitation for weak answers, since I know enough of the “core” of the Python language to be pretty certain that no such idiom exists, at least not one that would match the advantages (generality, legibility, ease of typing) of a dedicated method.
Try this:
Or, for python versions >= 2.7: