In Python, it's possible to extend a list in a lazy way by using itertools.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()
.
ChainMap is a data structure provided by the Python standard library that allows you to treat multiple dictionaries as one. The official documentation on ChainMap reads: A ChainMap groups multiple dicts or other mappings together to create a single, updateable view.
In Python, dictionaries (or “dicts”, for short) are a central data structure: Dicts store an arbitrary number of objects, each identified by a unique dictionary key. Dictionaries are often also called maps, hashmaps, lookup tables, or associative arrays.
Using map() function to transform Dictionaries in Python map() function iterated over all the items in dictionary and then applied passed lambda function on each item. Which in turn updated the value of each item and returns a copy of original dictionary with updated contents.
The mapping objects are used to map hash table values to arbitrary objects. In python there is mapping type called dictionary. It is mutable. The keys of the dictionary are arbitrary. As the value, we can use different kind of elements like lists, integers or any other mutable type objects.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With