Python--合并2个字典成1个新字典的9种方法

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
原文地址:https://www.cnblogs.com/ailiailan/p/12068097.html