1. 程式人生 > >collections.ChainMap類合並字典或映射

collections.ChainMap類合並字典或映射

3rd 修改 and 新的 map () child log body

## 使用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).

collections.ChainMap類合並字典或映射