Python中字典合并的实现方法
TableofContents
背景
Methon1:适用于Python3.5及以上版本呢
Method2:自定义函数
多个dict进行合并
背景
python中有时候需要将字典进行合并,今天我们来探讨下这个主题。
先来看看下面的运行结果:
1x={'a':1,'b':2}
2y={'b':4,'c':5}
3z=x.update(y)
4#学习python
来看看z的返回结果:
print(z)
None
发现z返回的是None值,并不是我们想要的结果。
再来看一下此时x的返回结果,发现x已经是合并的结果。
x
{'a':1,'b':4,'c':5}
那么有没有比较简单的实现方法呢。下面我们来探索一下:
Methon1:适用于Python3.5及以上版本呢
在Python3.5以上版本(含3.5),可以通过下列方法实现
z1={**x,**y}
z1
{'a':1,'b':4,'c':5}
Method2:自定义函数
如果在Python2或Python3.4以及低于3.4的版本,要实现两个dict的合并,该怎样做呢?
先定义一个函数,然后用自定义函数来运行:
1defmerge(x,y):
2z=x.copy()
3z.update(y)
4returnz
5
6z2=merge(x,y)
7z2
8
9{'a':1,'b':4,'c':5}
Method2在Python3.5以上版本也是可以运行的。
此外,请注意x中‘b’=2,y中‘b’=4,而运算结果中‘b’=4,是用y中‘b’的值来对字典进行更新。
多个dict进行合并
如果是多个dictionary需要进行合并呢?
同样可以通过自定义的形式来实现。
1defmerge_dicts(*dict_args):
2result={}
3foritemindict_args:
4result.update(item)
5returnresult
6
7x1={'a':1,'b':2}
8y1={'b':4,'c':5}
9x2={'d':8,'e':10}
10
11z3=merge_dicts(x1,y1,x2)
12z3
13
14{'a':1,'b':4,'c':5,'d':8,'e':10}
此方法在Python2和Python3下都是可以运行的。
以上内容为大家介绍了Python中字典合并的实现方法,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注IT培训机构:千锋教育。http://www.mobiletrain.org/

相关推荐HOT
更多>>
python中ndarray与list转换的方法
python中ndarray与list转换的方法在python数据类型中,list元素可以任意类型组合,而ndarray元素类型必须相同,但是ndarray可以更方便的对多维...详情>>
2023-11-10 08:51:14
python中OrdereDict如何使用?
python中OrdereDict如何使用?我们在对数据进行处理时,如果能够使它们保存顺序的排序,那么用起来会非常的便利。不过字典本身就是没有顺序的,...详情>>
2023-11-10 07:05:00
python中如何使用scipy.fftpack模块计算快速傅里叶变换?
python中如何使用scipy.fftpack模块计算快速傅里叶变换?在编程中,快速傅里叶变换是工程中非常有价值的一类算法,它可以将时域和频域的信号相互...详情>>
2023-11-10 05:50:23
zip()函数如何在python中遍历多个列表?
zip()函数如何在python中遍历多个列表?下面我们就python中zip的说明、语法、使用注意点进行讲解,然后带来遍历多个列表的实例。1、说明zip()函...详情>>
2023-11-10 05:38:33热门推荐
python concat函数有何用法?
沸python里函数装饰器怎么使用?
热如何实现python中的continue语句?
热python中的冒泡排序是什么?
新python中str函数是什么
如何使用python实现项目进度显示?
python中ndarray与list转换的方法
python复制文件的方法整理
Python中numpy数组如何添加元素
python有几种可视化图形库?
python中xlwings是什么?
python上下文管理器的基本介绍
Python自动化测试基础必备知识点一
python中OrdereDict如何使用?
技术干货






