Intersection_update for dicts?

I need a dictionary class that implements a method intersection_updatesimilar in spirit to dict.update, but restricting updates to, only those keys that are already present in the calling instance (see below for some implementation examples).

But, in the spirit of "Avoiding Wheel Rollback", before I leave the implementation (and write tests for, etc.) of the mapping class with this additional functionality, it does something similar in the more or less standard module


To be clear, the method intersection_updateI have in mind will do something like this:

def intersection_update(self, other):
    for k in self.viewkeys() & other.viewkeys():
        self[k] = other[k]

... although the actual implementation may try to perform some possible optimizations, for example, for example:

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]

: ", Python, [ intersection_update]?", , , , , "" Python, , , , , (, , ) .

+5
2

:

def dict_intersection(d1, d2):
    return dict((key, d2[key] or d1[key]) for key in frozenset(d1) & frozenset(d2))

, python >= 2.7:

def dict_intersection(d1, d2):
    return {key: d2[key] or d1[key] for key in d1.viewkeys() & d2.viewkeys()}
+1

, , , , dict .

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: kjo, iteritems

+2

All Articles