官术网_书友最值得收藏!

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:

主站蜘蛛池模板: 五莲县| 昌乐县| 巩义市| 瑞安市| 厦门市| 梅州市| 铜陵市| 文水县| 南和县| 阿巴嘎旗| 全椒县| 班玛县| 南丰县| 峨山| 牟定县| 芜湖县| 蓝田县| 若尔盖县| 鹤峰县| 抚顺市| 江孜县| 奎屯市| 龙门县| 神木县| 肇州县| 南江县| 林口县| 洪泽县| 红安县| 昆明市| 湘西| 永修县| 宾川县| 怀柔区| 丰镇市| 北宁市| 新乡县| 昌都县| 丘北县| 榆中县| 温泉县|