字典合并的方法比较多,可以参考下面:比较常用的有下面两种方法:
1.定义一个空字典d = {} 两次使用update方法向字典中添加元素
d1 = {'name': 'revotu', 'age': 99}
d2 = {'age': 24, 'sex': 'male'}
d.update(d1)
d.update(d2)
print(d)
2.z = d1.update(d2)
print(d1)
z为空,d1为合并后的字典
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
我有两个Python字典,如何合并它们呢?update()方法正是你所需要的。
>>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> z = x.update(y)
>>> print(z)
None
>>> x
{'a': 1, 'b': 10, 'c': 11}