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

原文地址:https://blog.csdn.net/yuxuan89814/article/details/129287100