开发者

Is there a chain for Python maps?

开发者 https://www.devze.com 2023-02-25 00:35 出处:网络
In Python, it\'s possible to extend a list in a lazy way by using itertools开发者_StackOverflow中文版.chain:

In Python, it's possible to extend a list in a lazy way by using itertools开发者_StackOverflow中文版.chain:

L = itertools.chain(L1, L2)

Is there a lazy map "gluing" operator? I.e.,

M = glue(M1, M2)

where

M['blah']

returns

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

and, M has appropriate generators for keys() and values().


Python 3.3 added collections.ChainMap that does exactly that.


It's straightforward to build a class to represent lazy evaluations against a list of maps, and tailor the behavior to your application. For example:

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())

Output:

1
2
['blah', 'duh']
[1, 2]
0

精彩评论

暂无评论...
验证码 换一张
取 消