# 如何快速合并两个字典

x = {'a':1,'b':2}y = {'b':10,'c':11}

fromcollectionsimportChainMapz = ChainMap(x, y)print(z)

# 字典的常用操作不变

print(list(z.values()))print(list(z.keys()))

ChainMap({‘a’: 20, ‘b’: 2}, {‘b’: 10, ‘c’: 11})

[11, 20, 2]

[‘c’, ‘a’, ‘b’]

print(z['b'])

2

z['a'] =20

print(x)

{‘a’: 20, ‘b’: 2}

z = {**x, **y}print(z)

{‘a’: 20, ‘b’: 10, ‘c’: 11}

amazing!

defmerge_two_dicts(x, y):

# 做一份潜复制

z = x.copy()

# 更新z中的键值

z.update(y)

returnzz = merge_two_dicts(x, y)print(z)

{‘a’: 20, ‘b’: 10, ‘c’: 11}

defmerge_dicts(*dict_args):

result = {}

fordictionaryindict_args: result.update(dictionary)

returnresult

x = {'a':1,'b':2}y = {'b':10,'c':11}z = merge_dicts(x, y)print(z)x['a'] =20print(x)print(z)z_ = {**x, **y}print(z_)x['a'] =30print(z_)

{‘a’: 1, ‘b’: 10, ‘c’: 11}

{‘a’: 20, ‘b’: 2}

{‘a’: 1, ‘b’: 10, ‘c’: 11}

{‘a’: 20, ‘b’: 10, ‘c’: 11}

{‘a’: 20, ‘b’: 10, ‘c’: 11}

• 发表于:
• 原文链接http://kuaibao.qq.com/s/20171216A0O08600?refer=cp_1026
• 腾讯「云+社区」是腾讯内容开放平台帐号（企鹅号）传播渠道之一，根据《腾讯内容开放平台服务协议》转载发布内容。
• 如有侵权，请联系 yunjia_community@tencent.com 删除。

2022-05-25

2018-07-06

2018-06-13

2018-04-12

2018-04-10

2022-05-25

2022-05-25