- Python Data Structures and Algorithms
- Benjamin Baka
- 268字
- 2021-07-09 19:45:04
ChainMaps
The collections.chainmap class was added in Python 3.2 and it provides a way to link a number of dictionaries, or other mappings, so that they can be treated as one object. In addition, there is a maps attribute, a new_child() method, and a parents property. The underlying mappings for ChainMap objects are stored in a list and are accessible using the maps[i] attribute to retrieve the ith dictionary. Note that even though dictionaries themselves are unordered, ChainMaps are an ordered list of dictionaries. ChainMap is useful in applications where we are using a number of dictionaries containing related data. The consuming application expects data in terms of a priority, where the same key in two dictionaries is given priority if it occurs at the beginning of the underlying list. ChainMap is typically used to simulate nested contexts such as when we have multiple overriding configuration settings. The following example demonstrates a possible use case for ChainMap:

The advantage of using ChainMaps, rather than just a dictionary, is that we retain previously set values. Adding a child context overrides values for the same key, but it does not remove it from the data structure. This can be useful for when we may need to keep a record of changes so that we can easily roll back to a previous setting.
We can retrieve and change any value in any of the dictionaries by providing the map() method with an appropriate index. This index represents a dictionary in the ChainMap. Also, we can retrieve the parent setting, that is, the default settings, by using the parents() method:

- 數據結構習題精解(C語言實現+微課視頻)
- Scratch 3.0少兒編程與邏輯思維訓練
- Learning Neo4j 3.x(Second Edition)
- Java性能權威指南(第2版)
- 微信公眾平臺開發:從零基礎到ThinkPHP5高性能框架實踐
- ANSYS Fluent 二次開發指南
- Learning Unity 2D Game Development by Example
- Python全棧數據工程師養成攻略(視頻講解版)
- Unity&VR游戲美術設計實戰
- 動手打造深度學習框架
- jQuery for Designers Beginner's Guide Second Edition
- 現代C:概念剖析和編程實踐
- Java 7 Concurrency Cookbook
- Learning iOS Penetration Testing
- 微信公眾平臺開發最佳實踐