下面的代码举例了8种合并两个字典的方法,并且做了个简单的性能测试
#!/usr/bin/python
import time
def f1(d1, d2):
return dict(d1, **d2)
def f2(d1, d2):
# only python2
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 f8(d1, d2):
# only python3
return {**d1, **d2}
def t(f, n):
try:
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))
except:
print('%s unsupport' % n)
t(f1, 'f1')
t(f2, 'f2')
t(f3, 'f3')
t(f4, 'f4')
t(f5, 'f5')
t(f6, 'f6')
t(f7, 'f7')
t(f8, 'f8')
下面是python2测试结果(f8语法不支持):
f1 cost:0.945858955383
f2 cost:2.12318110466
f3 cost:1.00671386719
f4 cost:0.839238882065
f5 cost:1.13564586639
f6 cost:1.44612598419
f7 cost:1.18877100945
下面是Python3上的结果(f2不支持,需改为return dict(list(d1.items()) + list(d2.items()))):
f1 cost:0.8159599304199219
f2 unsupport
f3 cost:0.8143870830535889
f4 cost:0.6823759078979492
f5 cost:0.9766209125518799
f6 cost:1.242981195449829
f7 cost:0.9813382625579834
f8 cost:0.6307079792022705
可以看出在Python2下f4最为高效,但该方法会修改到d1;
在Python3上整体效率都高于Python2的,f8效率最高,同时也不会对原字典造成修改。
七年前(2014)写的博客,那时候还在用Python2.7,现在基本都切换到Python3.7+了,建议还在用Python2的尽快拥抱Python3吧。
最后,感谢评论里提供f8方法的网友。