Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a chain for Python maps?

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

like image 212
Neil G Avatar asked Apr 16 '11 01:04

Neil G


People also ask

What is a chain map Python?

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.

Do maps exist in Python?

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.

Can you use map on dictionary Python?

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.

What is mapping object in Python?

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.


2 Answers

Python 3.3 added collections.ChainMap that does exactly that.

like image 126
Neil G Avatar answered Oct 05 '22 20:10

Neil G


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]
like image 45
samplebias Avatar answered Oct 05 '22 20:10

samplebias