python学习之字典合并

 1 """
 2 首先生成两个字典
 3 """
 4 dict_one = {'one': '1', 'two': '2'}
 5 dict_two = {'three': '3', 'tour': '4'}
 6 
 7 # 方法一: 使用uptate方法,把two字典更新至one字典中
 8 dict_one.update(dict_two)
 9 print(dict_one)
10 
11 # 方法二: 首先使用copy方法,把one字典进行了复制,然后使用update方法把two字典更新到three字典中
12 dict_three = dict_one.copy()
13 dict_three.update(dict_two)
14 print(dict_three)
15 
16 # 方法三:使用for循环, 利用迭代器(以(键,值)为元素的元组表示)
17 for k, y in dict_one.items():
18     dict_two[k] = y
19 print(dict_two)
20 
21 # 方法四:对字典two进行拆包,再把one和two的组合转成字典类型
22 dict_four = dict(dict_one, **dict_two)
23 print(dict_four)

如有疑问,欢迎来找茬......

posted @ 2019-11-17 15:23  一名小测试  阅读(210)  评论(0编辑  收藏  举报