python ChainMap的使用

链接字典

chainMap是逻辑上合并两个字典为一个逻辑单元,合并后的结构实际上是一个列表,只是逻辑上是仍然为一个字典(并未生成新的),对此列表的操作模拟了各种字典的操作。合并后的取值及操作仍然是对原始字典的操作。

相同的key值合并后取第一个字典里的值作为重复key的值,

from collections import ChainMap

dict1={"x":1,"y":3,"t":12}
dict2={"x":5,"z":3}

chain_dict=ChainMap(dict1,dict2)
#相同的key值合并后取第一个dict里的值作为重复key的值
print(chain_dict["x"])
print(chain_dict["z"])

结果:

1
3

对chain_dict的增删改查影响的都是第一个字典

from collections import ChainMap

dict1={"x":1,"y":3,"t":12}
dict2={"x":5,"z":3}

chain_dict=ChainMap(dict1,dict2)
#对chain_dict的增删改查影响的都是dict1
chain_dict["a"]=10
print(dict1)
chain_dict["x"]=100
print(dict1)
del dict1["t"]
print(dict1)
print(dict2)

 结果:

{'x': 1, 'y': 3, 't': 12, 'a': 10}
{'x': 100, 'y': 3, 't': 12, 'a': 10}
{'x': 100, 'y': 3, 'a': 10}
{'x': 5, 'z': 3}

maps属性可输出所以合并的字典

from collections import ChainMap
dict1={"x":1,"y":3,"t":12}
dict2={"x":5,"z":3}

chain_dict=ChainMap(dict1,dict2)


print(chain_dict.maps)

结果:

[{'x': 1, 'y': 3, 't': 12}, {'x': 5, 'z': 3}]
 

new_child()方法是在合并后的映射列表头部位置插入空映射{}
from collections import ChainMap
dict1={"x":1,"y":3,"t":12}
dict2={"x":5,"z":3}

chain_dict=ChainMap(dict1,dict2)


print(chain_dict.maps)
a=chain_dict.new_child()
print(a)
print(a.maps)

结果:

[{'x': 1, 'y': 3, 't': 12}, {'x': 5, 'z': 3}]
ChainMap({}, {'x': 1, 'y': 3, 't': 12}, {'x': 5, 'z': 3})
[{}, {'x': 1, 'y': 3, 't': 12}, {'x': 5, 'z': 3}]

new_child()可以衍生出parent()方法的使用,parent()其实是在合并后的映射列表去掉头部位置第一个映射后的结果:

from collections import ChainMap
dict1={"x":1,"y":3,"t":12}
dict2={"x":5,"z":3}

chain_dict=ChainMap(dict1,dict2)


print(chain_dict.maps)
a=chain_dict.new_child()
print(a)
print(a.maps)
b=a.parents
print("b=",b)
bb=b.parents
print("bb=",bb)

结果:

[{'x': 1, 'y': 3, 't': 12}, {'x': 5, 'z': 3}]
ChainMap({}, {'x': 1, 'y': 3, 't': 12}, {'x': 5, 'z': 3})
[{}, {'x': 1, 'y': 3, 't': 12}, {'x': 5, 'z': 3}]
b= ChainMap({'x': 1, 'y': 3, 't': 12}, {'x': 5, 'z': 3})
bb= ChainMap({'x': 5, 'z': 3})

链接字典的应用:

链接字典及它的new_child和parent方法特性适合处理作用域及查找链类似问题:

1,查找链

import builtins
pylookup = ChainMap(locals(), globals(), vars(builtins))

2,作用域

比如用户指定的命令行参数优先于环境变量的示例,而环境变量优先于默认值:

import os, argparse
 
defaults = {'color': 'red', 'user': 'guest'}
 
parser = argparse.ArgumentParser()
parser.add_argument('-u', '--user')
parser.add_argument('-c', '--color')
namespace = parser.parse_args()
command_line_args = {k:v for k, v in vars(namespace).items() if v}
 
combined = ChainMap(command_line_args, os.environ, defaults)
print(combined['color'])
print(combined['user'])

用例参考:python3的ChainMap_langb2014的博客-CSDN博客

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值