python 合并字典效率问题

  1. 原文地址: http://www.dewen.io/q/2002
  2. x = {'a':1, 'b': 2} ;
  3. y = {'b':10, 'c': 11}
  4. //方法一
  5. z = dict(x.items()+y.items());
  6. //方法二
  7. z = dict(z,**y)
  8. //方法三
  9. z = x.copy()
  10. z.update(y)
  11. //方法四
  12. z = (lambda a, b: (lambda a_copy: a_copy.update(b) or a_copy)(a.copy()))(x, y)

  1. In [17]: timeit.timeit("dict(x,**y)", "x = {'a':1, 'b': 2};y={'b':10, 'c':11}")
  2. Out[17]: 0.6188690662384033

  3. In [18]: timeit.timeit("dict(x.items()+y.items())", "x = {'a':1, 'b': 2};y={'b':10, 'c':11}")
  4. Out[18]: 1.8446910381317139

  5. In [19]: timeit.timeit("dict(x,**y)", "x = {'a':1, 'b': 2};y={'b':10, 'c':11}")
  6. Out[19]: 0.6554520130157471

  7. In [20]: timeit.timeit("z=x.copy();z.update(y)", "x = {'a':1, 'b': 2};y={'b':10, 'c':11}")
  8. Out[20]: 0.5006368160247803

  9. 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}")
  10. Out[21]: 1.0203309059143066

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值