python ChainMap如何使用
发布时间:2023-03-29 14:09:37 所属栏目:教程 来源:
导读: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"]) 结果: 对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,作用域 比如用户指定的命令行参数优先于环境变量的示例,而环境变量优先于默认值: 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']) (编辑:汽车网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
