链式Chainmap

python基础

浏览数:326

2019-8-28

使用ChainMap可以将多个字典串联起来,当做一个字典来处理

from collections import ChainMap

user_dict1 = {"a": "xiaohong", "b": "xiaohua"}
user_dict2 = {"c": "xiaopang", "d": "xiaoming"}

new_dict = ChainMap(user_dict1, user_dict2)

print(new_dict)
# ChainMap({'a': 'xiaohong', 'b': 'xiaohua'}, {'c': 'xiaopang', 'd': 'xiaoming'})

可以直接访问串联起来的数据

print(new_dict["c"])
# xiaopang

当不同的字典具有相同的主键的时候,在遍历串联之后的数据时,会只能遍历到之前的

user_dict1 = {"a": "xiaohong", "b": "xiaohua"}
user_dict2 = {"b": "xiaopang", "d": "xiaoming"}
new_dict = ChainMap(user_dict1, user_dict2)

for key, value in new_dict.items():
    print(key, value)

# d xiaoming
# b xiaohua
# a xiaohong

可以动态添加新的dict

# new_dict.new_child(new_dict)
#
# print(new_dict)
# for key, value in new_dict.items():
#     print(key, value)

maps 方法会将串联起来的字典以列表的形式展示

print(new_dict.maps)
# [{'a': 'xiaohong', 'b': 'xiaohua'}, {'c': 'xiaopang', 'd': 'xiaoming'}]

ChainMap 并不是对源数据的拷贝,而是 指向源数据

new_dict.maps[0]["a"] = "pangzi"

print(new_dict)
# ChainMap({'a': 'pangzi', 'b': 'xiaohua'}, {'c': 'xiaopang', 'd': 'xiaoming'})

作者:海贼之路飞