collections.ChainMap对象

本文主要介绍了Python中ChainMap的使用。通过示例展示了如何创建ChainMap对象,以及对其进行元素的访问、增加、删除和修改操作。还介绍了new_child()、parents、maps等方法的使用,同时说明了有重复键时的访问规则和ChainMap使用字典引用的特性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

例子:

from collections import ChainMap

combined = ChainMap({"a": "A"}, {"b": "B"}, {"c": "C"}, {"d": "D"})

# 访问元素

element_a = combined["a"]

# 增删,修改只对第一个dict有用

# 增加元素

combined["big_a"] = "big_A"      #  combined = ChainMap({'a': 'A', 'big_a': 'big_A'}, {'b': 'B'}, {'c': 'C'}, {'d': 'D'})

combined["b"] = "big_B"   #  ChainMap({'a': 'A', 'big_a': 'big_A', 'b': 'big_B'}, {'b': 'B'}, {'c': 'C'}, {'d': 'D'})

# 删除元素

del combined["b"]   # ChainMap({'a': 'A', 'big_a': 'big_A'}, {'b': 'B'}, {'c': 'C'}, {'d': 'D'})

# new_child(),用一个空dict插到第一个dict前面后构成的ChainMap

to_child = combined.new_child()      # to_child = ChainMap({}, {'a': 'A', 'big_a': 'big_A'}, {'b': 'B'}, {'c': 'C'}, {'d': 'D'})

# parents,除去第一个dict后构成的ChainMap

to_parents = combined.parents       # to_parents = ChainMap({'b': 'B'}, {'c': 'C'}, {'d': 'D'})

# maps,得到成员dict的列表

to_maps = combined.maps              # to_maps = [{'a': 'A', 'big_a': 'big_A'}, {'b': 'B'}, {'c': 'C'}, {'d': 'D'}]

# 有重复keys时访问元素,在前面的才是最终会被访问的

com_repeat = ChainMap({"a": "A",  "d": "good_D"}, {"b": "B"}, {"c": "C"}, {"d": "D"})

element_d = com_repeat["d"]           # element_d = "good_D"

# 注意,构成ChainMap是使用dict的引用,因而原来的dict改变,会导致ChainMap对象跟着改变

dict1, dict2, dict3, dict4 = {"a": "A",  "d": "good_D"}, {"b": "B"}, {"c": "C"}, {"d": "D"}

com_new = ChainMap(dict1, dict2, dict3, dict4)

dict4["d"] = "big_D"                          # com_new = ChainMap({'a': 'A', 'd': 'good_D'}, {'b': 'B'}, {'c': 'C'}, {'d': 'big_D'})

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值