## 使用update()方法或者ChainMap类合并字典或映射
1 # 使用update()方法合并 2 3 a = {‘x‘: 1, ‘z‘: 3} 4 b = {‘y‘: 2, ‘z‘: 4} 5 merged = dict(b) # 创建一个新字典 6 print(merged) 7 # {‘y‘: 2, ‘z‘: 4} 8 merged.update(a) # 更新字典数据(合并) 9 print(merged) 10 # {‘y‘: 2, ‘z‘: 3, ‘x‘: 1} 11 12 a[‘x‘] = 10 # 对原有字典的改变不会影响合并后的字典 13 print(merged) 14 # {‘y‘: 2, ‘z‘: 3, ‘x‘: 1} 15 16 17 18 # 使用collections.ChainMap()类 19 from collections import ChainMap 20 21 22 a = {‘x‘: 1, ‘z‘: 3} 23 b = {‘y‘: 2, ‘z‘: 4} 24 c = ChainMap(a, b) 25 print(c) 26 # ChainMap({‘x‘: 1, ‘z‘: 3}, {‘y‘: 2, ‘z‘: 4}) 27 28 29 # 数据的读取总是从第一个字典开始查找,找不到再从第二个中查找 30 print(c[‘x‘]) 31 # 1 32 print(c[‘y‘]) 33 # 2 34 print(c[‘z‘]) 35 # 3 36 37 38 # 数据的增加或者删除操作总是针对第一个字典 39 c[‘w‘] = 4 40 print(c) 41 # ChainMap({‘x‘: 1, ‘z‘: 3, ‘w‘: 4}, {‘y‘: 2, ‘z‘: 4}) 42 43 del c[‘w‘] 44 print(c) 45 # ChainMap({‘x‘: 1, ‘z‘: 3}, {‘y‘: 2, ‘z‘: 4}) 46 47 del c[‘y‘] # 无法删除第二个字典中的键值对 48 # KeyError: ‘y‘ 49 # KeyError: "Key not found in the first mapping: ‘y‘" 50 51 52 # 对原有字典的操作会影响合并的字典 53 a = {‘x‘: 1, ‘z‘: 3} 54 b = {‘y‘: 2, ‘z‘: 4} 55 c = ChainMap(a, b) 56 print(c) 57 # ChainMap({‘x‘: 1, ‘z‘: 3}, {‘y‘: 2, ‘z‘: 4}) 58 print(c[‘x‘]) 59 # 1 60 print(c[‘y‘]) 61 # 2 62 print(c[‘z‘]) 63 # 3 64 65 a[‘x‘] = 5 # 修改原有字典的值 66 print(c[‘x‘]) # 合并的字典受到影响 67 # 5 68 69 70 # ChainMap()对象支持大多数字典的操作 71 print(len(c)) 72 # 3 73 print(list(c.keys())) 74 # [‘x‘, ‘y‘, ‘z‘] 75 print(list(c.values())) 76 # [5, 2, 3] 77 78 79 # 添加或删除新的字典 80 values = ChainMap() 81 values[‘x‘] = 1 82 values = values.new_child() # 添加一个空白字典 83 print(values) 84 # ChainMap({}, {‘x‘: 1}) 85 values[‘x‘] = 2 # 给空白字典添加内容 86 print(values) 87 # ChainMap({‘x‘: 2}, {‘x‘: 1}) 88 values = values.new_child() 89 values[‘x‘] = 3 90 print(values) 91 # ChainMap({‘x‘: 3}, {‘x‘: 2}, {‘x‘: 1}) 92 93 # 删除第一个字典 94 values = values.parents 95 print(values) 96 # ChainMap({‘x‘: 2}, {‘x‘: 1}) 97 values = values.parents 98 print(values) 99 # ChainMap({‘x‘: 1})
参考资料:
Python Cookbook, 3rd edition, by David Beazley and Brian K. Jones (O’Reilly).
原文地址:https://www.cnblogs.com/hycstar/p/9352125.html
时间: 2024-10-14 15:45:03