Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

intersection_update for dicts?

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.

like image 798
kjo Avatar asked Sep 27 '12 15:09

kjo


1 Answers

Here is an pseudo code which you may use with existing update function, but any ways if you want to extend dictionary then your piece of code is also valid - but that would add some extra headache of using your class of dict everywhere.

In [1]: x = dict(name='abc', age=23)

In [2]: y = dict(name='xyz', notes='Note 123', section=None)

In [3]: #x.update(dict((k,y[k]) for k in y if k in x))

In [3]: x.update((k,v) for k,v in y.iteritems() if k in x)

In [4]: x
Out[4]: {'age': 23, 'name': 'xyz'}

EDIT: updated the code as per kjo's comments using iteritems method

like image 69
shahjapan Avatar answered Nov 08 '22 00:11

shahjapan