# 如何快速合并两个字典

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}

774 篇文章98 人订阅

0 条评论

## 相关文章

### Python 数据类型

Python主要数据类型包括list（列表）、tuple（元组）、dict（字典）和set（集合）等对象，下面逐一介绍这些Python数据类型。

9500

19650

182100

28570

321110

### CC++变参函数

C语言中，有时需要变参函数来完成特殊的功能，比如C标准库函数printf()和scanf()。C中提供了省略符“…”能够帮主programmer完成变参函数的书...

9810

### Java基础之String中equals,声明方式,等大总结

转载请注明出处：http://blog.csdn.net/dmk877/article/details/49420141

9320

8310

42660

### 01 - JavaSE之基础及面向对象

byte(-128 ~ 127) short(-32768 ~ 32767) int(-2147483648 ~ 2147483647)

18140