ChainMap类合并字典或映射

ChainMap类合并字典或映射

## 使用update()方法或者ChainMap类合并字典或映射

 # 使用update()方法合并

 a = {'x': 1, 'z': 3}
b = {'y': 2, 'z': 4}
merged = dict(b) # 创建一个新字典
print(merged)
# {'y': 2, 'z': 4}
merged.update(a) # 更新字典数据(合并)
print(merged)
# {'y': 2, 'z': 3, 'x': 1} a['x'] = 10 # 对原有字典的改变不会影响合并后的字典
print(merged)
# {'y': 2, 'z': 3, 'x': 1} # 使用collections.ChainMap()类
from collections import ChainMap a = {'x': 1, 'z': 3}
b = {'y': 2, 'z': 4}
c = ChainMap(a, b)
print(c)
# ChainMap({'x': 1, 'z': 3}, {'y': 2, 'z': 4}) # 数据的读取总是从第一个字典开始查找,找不到再从第二个中查找
print(c['x'])
#
print(c['y'])
#
print(c['z'])
# # 数据的增加或者删除操作总是针对第一个字典
c['w'] = 4
print(c)
# ChainMap({'x': 1, 'z': 3, 'w': 4}, {'y': 2, 'z': 4}) del c['w']
print(c)
# ChainMap({'x': 1, 'z': 3}, {'y': 2, 'z': 4}) del c['y'] # 无法删除第二个字典中的键值对
# KeyError: 'y'
# KeyError: "Key not found in the first mapping: 'y'" # 对原有字典的操作会影响合并的字典
a = {'x': 1, 'z': 3}
b = {'y': 2, 'z': 4}
c = ChainMap(a, b)
print(c)
# ChainMap({'x': 1, 'z': 3}, {'y': 2, 'z': 4})
print(c['x'])
#
print(c['y'])
#
print(c['z'])
# a['x'] = 5 # 修改原有字典的值
print(c['x']) # 合并的字典受到影响
# # ChainMap()对象支持大多数字典的操作
print(len(c))
#
print(list(c.keys()))
# ['x', 'y', 'z']
print(list(c.values()))
# [5, 2, 3] # 添加或删除新的字典
values = ChainMap()
values['x'] = 1
values = values.new_child() # 添加一个空白字典
print(values)
# ChainMap({}, {'x': 1})
values['x'] = 2 # 给空白字典添加内容
print(values)
# ChainMap({'x': 2}, {'x': 1})
values = values.new_child()
values['x'] = 3
print(values)
# ChainMap({'x': 3}, {'x': 2}, {'x': 1}) # 删除第一个字典
values = values.parents
print(values)
# ChainMap({'x': 2}, {'x': 1})
values = values.parents
print(values)
# ChainMap({'x': 1})

参考资料:
  Python Cookbook, 3rd edition, by David Beazley and Brian K. Jones (O’Reilly).

05-19 06:11