- 原文地址: http://www.dewen.io/q/2002
- x = {'a':1, 'b': 2} ;
- y = {'b':10, 'c': 11}
- //方法一
- z = dict(x.items()+y.items());
- //方法二
- z = dict(z,**y)
- //方法三
- z = x.copy()
- z.update(y)
- //方法四
- z = (lambda a, b: (lambda a_copy: a_copy.update(b) or a_copy)(a.copy()))(x, y)
- In [17]: timeit.timeit("dict(x,**y)", "x = {'a':1, 'b': 2};y={'b':10, 'c':11}")
- Out[17]: 0.6188690662384033
-
- In [18]: timeit.timeit("dict(x.items()+y.items())", "x = {'a':1, 'b': 2};y={'b':10, 'c':11}")
- Out[18]: 1.8446910381317139
-
- In [19]: timeit.timeit("dict(x,**y)", "x = {'a':1, 'b': 2};y={'b':10, 'c':11}")
- Out[19]: 0.6554520130157471
-
- In [20]: timeit.timeit("z=x.copy();z.update(y)", "x = {'a':1, 'b': 2};y={'b':10, 'c':11}")
- Out[20]: 0.5006368160247803
-
- In [21]: timeit.timeit("(lambda a, b: (lambda a_copy: a_copy.update(b) or a_copy)(a.copy()))(x, y)", "x = {'a':1, 'b': 2};y={'b':10, 'c':11}")
- Out[21]: 1.0203309059143066