collections.ChainMap对象

例子:

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'})

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值