Advanced collections
The following collections are mostly just extensions of base collections, some of them fairly simple and others a bit more advanced. For all of them though, it is important to know the characteristics of the underlying structures. Without understanding them, it will be difficult to comprehend the characteristics of these collections.
There are a few collections that are implemented in native C code for performance reasons, but all of them can easily be implemented in pure Python as well.
ChainMap – the list of dictionaries
Introduced in Python 3.3, ChainMap
allows you to combine multiple mappings (dictionaries for example) into one. This is especially useful when combining multiple contexts. For example, when looking for a variable in your current scope, by default, Python will search in locals()
, globals()
, and lastly builtins
.
Normally, you would do something like this:
import builtins builtin_vars = vars(builtins) if key in locals(): value = locals()[key]...