filmov
tv
Python:ChainMap Collections Module in Python

Показать описание
Get introduced to Python’s collections module and its datatypes.
We’ll cover the following
Overview of ChainMap
Python’s collections module has specialized container datatypes that can be used to replace Python’s general-purpose containers (dict, tuple, list, and set). We will be studying the following parts of this module:
ChainMap
counter
defaultdict
deque
namedtuple
OrderedDict
There is a sub-module of collections called abc or Abstract Base Classes. These will not be covered in this chapter.
Let’s get started with the ChainMap container!
Overview of ChainMap
A ChainMap is a class that provides the ability to link multiple mappings together such that they end up being a single unit. If we look at the example below, we will notice that it accepts maps, which means that a ChainMap will accept any number of mappings or dictionaries and turn them into a single view that we can update.
Here we import ChainMap from our collections module (Line 1). Next we create three dictionaries (Lines 2-4). Then we create an instance of our ChainMap by passing in the three dictionaries that we just created (Line 5). Finally, we try accessing one of the keys in our ChainMap (Line 6). When we do this, the ChainMap will go through each map in order to see if that key exists and has a value. If it does, then the ChainMap will return the first value it finds that matches the corresponding key.
This is especially useful if we want to set up defaults. Let’s pretend that we want to create an application that has some defaults. The application will also be aware of the operating system’s environment variables. If there is an environment variable that matches one of the keys that we are defaulting to in our application, the environment will override our default. Let’s further pretend that we can pass arguments to our application. These arguments take precedence over the environment and the defaults. This is one place where a ChainMap can really shine. Let’s look at a simple example that’s based on one from Python’s documentation: