Is there a chain for Python maps?

In Python, you can extend a list in a lazy way using itertools.chain:

L = itertools.chain(L1, L2)

Is there a lazy card sticking operator? I.e.

M = glue(M1, M2)

Where

M['blah']

returns

M1['blah'] if 'blah' in M1 else M2['blah']

and Mhave corresponding generators for keys()and values().

+5
source share
2 answers

Python 3.3 added collections.ChainMap , which does just that.

+5
source

Just create a class to represent lazy grades against a list of maps and adapt the behavior to your application. For instance:

from UserDict import DictMixin

class Map(object, DictMixin):
    def __init__(self, *maps):
        self.maps = maps
    def __getitem__(self, key):
        for m in self.maps:
            if key in m:
                return m[key]
    def keys(self):
        return list(self.iterkeys())
    def iterkeys(self):
        return (k for m in self.maps for k in m.iterkeys())
    def values(self):
        return list(self.itervalues())
    def itervalues(self):
        return (v for m in self.maps for v in m.itervalues())

def glue(*maps):
    return Map(*maps)

M1 = {'blah': 1}
M2 = {'duh': 2}

M = glue(M1, M2)
print M['blah']
print M['duh']
print list(M.keys())
print list(M.values())

Conclusion:

1
2
['blah', 'duh']
[1, 2]
+4
source

All Articles