本文摘自php中文网,作者伊谢尔伦,侵删。
这篇文章主要介绍了Python合并两个字典的常用方法与效率比较,实例分析并对比了Python合并字典的常用方法,需要的朋友可以参考下本文实例讲述了Python合并两个字典的常用方法与效率比较。分享给大家供大家参考。具体分析如下:
下面的代码举例了5种合并两个字典的方法,并且做了个简单的性能测试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | import time
def f1(d1, d2):
return dict (d1, * * d2)
def f2(d1, d2):
return dict (d1.items() + d2.items())
def f3(d1, d2):
d = d1.copy()
d.update(d2)
return d
def f4(d1, d2):
d1.update(d2)
return d1
def f5(d1, d2):
d = dict (d1)
d.update(d2)
return d
def f6(d1, d2):
return ( lambda a, b: ( lambda a_copy: a_copy.update(b) or a_copy)(a.copy()))(d1, d2)
def f7(d1, d2):
d = {}
d.update(d1)
d.update(d2)
return d
def t(f, n):
st = time.time()
for i in range ( 1000000 ):
dic1 = { 'a' : 'AA' , 'b' : 'BB' , 'c' : 'CC' }
dic2 = { 'A' : 'aa' , 'B' : 'bb' , 'C' : 'cc' }
f(dic1, dic2)
et = time.time()
print '%s cost:%s' % (n, et - st)
t(f1, 'f1' )
t(f2, 'f2' )
t(f3, 'f3' )
t(f4, 'f4' )
t(f5, 'f5' )
t(f6, 'f6' )
t(f7, 'f7' )
|
除了f4方法会对字典d1造成破坏性修改之外,另外的几种方法都是把合并的结果作为新的字典返回。
下面是测试结果:
1 2 3 4 5 6 7 | f1 cost: 2.382999897
f2 cost: 4.45399999619
f3 cost: 3.02100014687
f4 cost: 1.73000001907
f5 cost: 2.3710000515
f6 cost: 2.89700007439
f7 cost: 2.35600018501
|
可以看出f4最为高效,如果不需要保留原字典的话推荐使用f4方法。
以上就是Python合并两个字典的效率实例比较的详细内容,更多文章请关注木庄网络博客!!
相关阅读 >>
用Python画星空源代码是什么?
Python中rjust是什么意思
Python如何实现注册登录系统的实例详解
如何使用Python画曲线图
列表、元组、字符串是Python的什么序列?
Python怎么安装词云wordcloud
使用pandas进行数据处理之 dataframe篇
Python numpy函数中linspace实现创建等差数列的实例分享
Python实现求一个集合所有子集的示例
Python pandas中dataframe类型数据操作函数的方法
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » Python合并两个字典的效率实例比较