[PYTHON] Main features of ChainMap

Starting with Python 3.3, a class called ChainMap in the collections standard library is available, but I will write down the main features as a memorandum.

ChainMap is used to collect multiple dictionaries to make one dictionary.

To do the same with dict, merge multiple dictionaries and include the elements of the original dictionary, as described in this article. I think I'll create a new dictionary.

ChainMap, on the other hand, does not copy elements into the new object, but keeps the original dictionary as a reference, so you don't have to update the ChainMap object if the original dictionary changes.

For example, consider the following sample.

python


from collections import ChainMap

d1 = {'A': 1, 'B':2}
d2 = {'C': 3, 'D':4}

cm = ChainMap(d1, d2)

Now, if you add an element to d1, you can see that you can get that element with cm as well.

python


>>> d1['E'] = 5
>>> cm['E']
5

You can get the original dictionary with the maps property.

python


>>> cm.maps
[{'E': 5, 'B': 2, 'A': 1}, {'D': 4, 'C': 3}]

If there are duplicate keys between the original dictionaries, the element in the previous dictionary takes precedence.

python


>>> d1['D'] = 6
>>> cm.maps
[{'E': 5, 'B': 2, 'A': 1, 'D': 6}, {'D': 4, 'C': 3}]
>>> cm['D']
6

Also, the original dictionary is not limited to the built-in dict object, you can specify a Mapping object. The following example uses ʻUserDict` from the same standard library as the source dictionary.

python


from collections import UserDict

class MyDict(UserDict):

    def __getitem__(self, key):
        if key not in self.data:
            return 'Not found'
        else:
            return self.data[key]

md1 = MyDict(d1)
md2 = MyDict(d2)

cm2 = ChainMap(md1, md2)

In this example, even if md2 has the key C, __getitem__ of md1 will be called first, so "Not found" will be returned.

python


>>> cm2['C']
'Not found'

Recommended Posts

Main features of ChainMap
Features of Go language
Features of programming languages [Memo]
About the features of Python
Train_test_split of features held by dict
Features of pd.NA in pandas 1.0.0 (rc0)
Master the rich features of IPython
Mastering the rich features of IPython (2)
Features of symbolic and hard links
Correlation visualization of features and objective variables
[Basics of python basics] Why do __name__ == "__main__"