daily pastebin goal
69%
SHARE
TWEET

Untitled

a guest Jan 21st, 2019 68 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # 有多个 dict,现在需要找出哪个 dict 包含特定 key
  2. # ChainMap 会将多个 dict 合并为一个,这个合并不是真的合并,也不是创建了一个新的包含所有 dict 的 dict,而是生成了一个列表,容纳这些 dict,并且这个列表支持很多 dict 的 api,因此表现的像是一个新的 dict
  3.  
  4. a = {'x': 1, 'z': 3 }
  5. b = {'y': 2, 'z': 4 }
  6.  
  7. from collections import ChainMap c = ChainMap(a,b)
  8.  
  9. print(c['x']) # Outputs 1 (from a)
  10. print(c['y']) # Outputs 2 (from b)
  11. print(c['z']) # Outputs 3 (from a)。重复的 key 只会取最先出现的 dict 中的值
  12.  
  13. len(c) # 3
  14. list(c.keys()) #['x', 'y', 'z']
  15. list(c.values()) # [1, 2, 3]
  16.  
  17. # 如果是赋值或删除操作,则只会对第一个 dict 生效
  18. c['z'] = 10 # a['z'] 也变成了 10,但是 b 未受影响
  19. c['w'] = 40 # a 现在也有了 a['w']==40
  20. del c['x'] # a 中的 'x' 被删除了
  21. del c['y'] # 报错,因为 a 中没有 'y' 这个 key
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top