d1 = {'name': 'revotu', 'age': 99} d2 = {'age': 24, 'sex': 'male'} 輸出: {'name': 'revotu', 'age': 24, 'sex': 'male'} # d = {} # d.update(d1) # 方法1,使用兩次update方法向字典中添加元素 # d.update(d2) # print(d)
# d = d1.copy() # 方法2,先複製,後更新 # d.update(d2) # print(d)
# d = dict(d1) # 方法3,字典構造器 # d.update(d2) # print(d)
# d = dict(d1, **d2) # 方法4,關鍵字參數hack # print(d) # 只有一行代碼,看上去很酷,可是有一個問題,這種hack技巧只有在字典的鍵是字符串時纔有效。
# d = {k: v for d in [d1, d2] for k, v in d.items()} # 方法5,字典推導式,字典推導式方法知足要求,只是嵌套的字典推導式,不那麼清晰,不易於理解。 # print(d)
# d = dict(list(d1.items()) + list(d2.items())) # 方法6,元素拼接 # print(d)
# d = dict(chain(d1.items(), d2.items())) # 方法7,chain items from itertools import chain # print(d)
# d = dict(ChainMap(d1, d2)) # 方法8,itemscollections.ChainMap能夠將多個字典或映射,在邏輯上將它們合併爲一個單獨的映射結構 # print(d) # 這種方法也很pythonic,並且也是通用方法 from collections import ChainMap
d = {**d1, **d2} # 方法9,字典拆分
print(d) # 在Python3.5+中,可使用一種全新的字典合併方式,這行代碼很pythonic