ChainMap
from collections import ChainMap
user_dict1 = {'a':"rio1", "b":"rio2"}
user_dict2 = {'b':"rio3", "d":"rio3"}
for key, value in user_dict1.item():
print(key,value)
for key, value in user_dict2.item():
print(key,value)
如果类似上面的dict定义了多个,就需要分别去遍历多次item
ChainMap可以把所有dict连接起来一起遍历。
new_dict = ChainMap(user_dict1,user_dict2)
for key, value in new_dict.item():
xxxxxx
如果两个字典存在相同的key,只会遍历先找到的key,后面出现相同的key都不会遍历
在原来的chainmap字典中再动态新增字典,返回一个新的ChainMap
new_chainmap = new_dict.new_child( {"aa":11,“bb":22} )
以列表形式把数据展示出来
print(new_dict.maps)
=> [{'a':"rio1", "b":"rio2"}, {'b':"rio3", "d":"rio3"}]
ChainMap并不是把多个数据合并变成一个dict,而是在上面加了一个访问迭代器,并没有拷贝到新的变量里。
new_dict.maps[0]['a'] = 'rio'
for key, value in new_dict.item():
print(key,value)
ChainMap(dict1, dict2)
会跳过相同的键
生成迭代器而不是生成新拷贝
new_dict.maps
from collections import ChainMap
d1 = {"a": "aa", "b": "bb"}
d2 = {"b": "bbb", "c": "cc"}
new_dict = ChainMap(d1, d2)
print(new_dict.maps)
new_dict.maps[0]["a"] = "aaa"
for k, v in new_dict.items():
print(k, v)
"""
ChainMap将多个字典连接起来,让我们可以很方便的遍历这些字典
其子方法:
items(): 遍历这个字典
new_child(): 添加字典元素
maps属性:以列表的形式将字典数据展示出来
"""
from collections import ChainMap
if __name__ == "__main__":
user_dict1 = {"a": "AA", "b": "BB"}
user_dict2 = {"b": "BBB", "c": "CC", "d": "DD"}
for key, value in user_dict1.items(): # 遍历字典
print(key, value)
for key, value in user_dict2.items():
print(key, value)
print("-----------------")
new_dict = ChainMap(user_dict1, user_dict2)
for key,value in new_dict.items():
print(key, value)
print(new_dict)
print(new_dict["c"]) # 取值key对应的值
new_dict.new_child({"aa":"AAAAA", "bb":"BBBBB"})
print(new_dict)
print(new_dict.maps) # 以列表的形式将字典数据展示出来
new_dict.maps[0]["a"] = "Hello World" # 将字典的第0个元素的a的值变为Hello World
print(new_dict)