Python|合并两个字典的8种方法

本文详细介绍了在Python中通过update(),**操作符,|运算符(3.9版本),for循环,ChainMap,dict构造函数和reduce()等方法来合并字典。每个方法都有实例演示和输出结果。
摘要由CSDN通过智能技术生成

在Python中,有多种方法可以通过使用各种函数和构造函数来合并字典。在本文中,我们将讨论一些合并字典的方法。

1. 使用方法update()

通过使用Python中的update()方法,可以将一个列表合并到另一个列表中。但是在这种情况下,第二个列表被合并到第一个列表中,并且没有创建新的列表。它返回None。

示例:

 1def merge(dict1, dict2):  
 2    return(dict2.update(dict1))  
 3  
 4  
 5# Driver code  
 6dict1 = {'a': 10, 'b': 8}  
 7dict2 = {'d': 6, 'c': 4}  
 8  
 9# This returns None  
10print(merge(dict1, dict2))  
11  
12# changes made in dict2  
13print(dict2)

输出

1None  
2{'c': 4, 'a': 10, 'b': 8, 'd': 6}  


2. 使用 ** 操作符

这通常被认为是Python中的一个技巧,其中使用单个表达式合并两个字典并存储在第三个字典中。使用 ** [星星]是一种快捷方式,它允许您直接使用字典将多个参数传递给函数。使用此方法,我们首先将第一个字典的所有元素传递到第三个字典,然后将第二个字典传递到第三个字典。这将替换第一个字典的重复键。

1def merge(dict1, dict2):  
2    res = {**dict1, **dict2}  
3    return res  
4  
5# Driver code  
6dict1 = {'a': 10, 'b': 8}  
7dict2 = {'d': 6, 'c': 4}  
8dict3 = merge(dict1, dict2)  
9print(dict3)  


输出

1{'a': 10, 'b': 8, 'd': 6, 'c': 4}  


3. 使用 ‘|’ 运算符 (Python 3.9)

在Python的3.9中,现在我们可以使用“|“运算符来合并两个字典。这是一种非常方便的字典合并方法。

1def merge(dict1, dict2):  
2    res = dict1 | dict2  
3    return res  
4  
5# Driver code  
6dict1 = {'x': 10, 'y': 8}  
7dict2 = {'a': 6, 'b': 4}  
8dict3 = merge(dict1, dict2)  
9print(dict3)  


输出

1{'x': 10, 'a': 6,  'b': 4, 'y': 8}  


4. 使用for循环和keys()方法
 1def merge(dict1, dict2):  
 2    for i in dict2.keys():  
 3        dict1[i]=dict2[i]  
 4    return dict1  
 5  
 6# Driver code  
 7dict1 = {'x': 10, 'y': 8}  
 8dict2 = {'a': 6, 'b': 4}  
 9dict3 = merge(dict1, dict2)  
10print(dict3)

输出

1{'x': 10, 'y': 8, 'a': 6, 'b': 4}  


5. 使用ChainMap

在Python中合并字典的一种新方法是使用collections模块中的内置ChainMap类。这个类允许您创建多个字典的单个视图,对ChainMap所做的任何更新或更改都将反映在底层字典中。

以下是如何使用ChainMap合并两个字典的示例:

 1from collections import ChainMap  
 2  
 3# create the dictionaries to be merged  
 4dict1 = {'a': 1, 'b': 2}  
 5dict2 = {'c': 3, 'd': 4}  
 6  
 7# create a ChainMap with the dictionaries as elements  
 8merged_dict = ChainMap(dict1, dict2)  
 9  
10# access and modify elements in the merged dictionary  
11print(merged_dict['a'])  # prints 1  
12print(merged_dict['c'])  # prints 3  
13merged_dict['c'] = 5  # updates value in dict2  
14print(merged_dict['c'])  # prints 5  
15  
16# add a new key-value pair to the merged dictionary  
17merged_dict['e'] = 6  # updates dict1  
18print(merged_dict['e'])  # prints 6

输出

11  
23  
35  
46  


使用ChainMap合并字典是一种简洁高效的方法,并且允许您轻松地更新和修改合并后的字典。

6. 使用dict构造函数
 1def merge_dictionaries(dict1, dict2):  
 2    merged_dict = dict1.copy()  
 3    merged_dict.update(dict2)  
 4    return merged_dict  
 5  
 6# Driver code  
 7dict1 = {'x': 10, 'y': 8}  
 8dict2 = {'a': 6, 'b': 4}  
 9  
10print(merge_dictionaries(dict1, dict2))

输出

1{'x': 10, 'y': 8, 'a': 6, 'b': 4}  


7. 使用dict构造函数和union运算符(|)

此方法使用dict()构造函数和联合运算符(|)合并两个字典。union运算符组合两个字典的键和值,并且两个字典中的任何公共键从第二个字典中获取值。

 1# method to merge two dictionaries using the dict() constructor with the union operator (|)  
 2def merge(dict1, dict2):  
 3    # create a new dictionary by merging the items of the two dictionaries using the union operator (|)  
 4    merged_dict = dict(dict1.items() | dict2.items())  
 5    # return the merged dictionary  
 6    return merged_dict  
 7  
 8# Driver code  
 9dict1 = {'a': 10, 'b': 8}  
10dict2 = {'d': 6, 'c': 4}  
11  
12# merge the two dictionaries using the Merge() function  
13merged_dict = merge(dict1, dict2)  
14  
15# print the merged dictionary  
16print(merged_dict)

输出

1{'d': 6, 'b': 8, 'c': 4, 'a': 10}  


8. 使用reduce()方法
 1from functools import reduce  
 2  
 3def merge_dictionaries(dict1, dict2):  
 4    merged_dict = dict1.copy()  
 5    merged_dict.update(dict2)  
 6    return merged_dict  
 7  
 8  
 9dict1 = {'a': 10, 'b': 8}  
10dict2 = {'d': 6, 'c': 4}  
11  
12dict_list = [dict1, dict2]  # Put the dictionaries into a list  
13  
14result_dict = reduce(merge_dictionaries, dict_list)  
15  
16print(result_dict)

输出

1{'a': 10, 'b': 8, 'd': 6, 'c': 4}  


---------------------------END---------------------------

▍学习资源推荐

零基础Python学习资源介绍

👉Python学习路线汇总👈
Python所有方向的技术点做的整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。(学习教程文末领取哈)
在这里插入图片描述

👉Python必备开发工具👈
在这里插入图片描述

温馨提示:篇幅有限,已打包文件夹,获取方式在:文末

👉Python学习视频600合集👈
观看零基础学习视频,看视频学习是最快捷也是最有效果的方式,跟着视频中老师的思路,从基础到深入,还是很容易入门的。
在这里插入图片描述

👉实战案例👈
光学理论是没用的,要学会跟着一起敲,要动手实操,才能将自己的所学运用到实际当中去,这时候可以搞点实战案例来学习。
在这里插入图片描述

👉100道Python练习题👈
检查学习结果。
在这里插入图片描述
👉面试刷题👈
在这里插入图片描述在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

资料领取

上述这份完整版的Python全套学习资料已经上传CSDN官方,朋友们如果需要可以微信扫描下方CSDN官方认证二维码输入“领取资料” 即可领取。

  • 6
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值