Python 字典的合并效率

在 Python 编程中,字典的使用频率非常高,合并操作也很常见。

x = {'name':'Eric', 'age':28}
y = {'age':29, 'hobby':['sport', 'travel']}

例如要合并这两个字典:更新其中某项,并添加新项。你能想到什么办法?

  1. update 方法

    z = x.copy()
    z.update(y)

  2. 使用 dict() 函数的字典参数

    z = dict(x, **y)

  3. items 变换

    z = dict(x.items() + y.items())

  4. lambda 表达式

    z = (lambda a, b: (lambda a_copy: a_copy.update(b) or a_copy)(a.copy()))(x, y)

这些方法都可以达到要求,哪种效率最高呢?

我们可以使用 timeit 模块来测试它们的运行效率。

import timeit

# 1 update 方法
timeit.timeit("z = x.copy(); z.update(y)", "x = {'name':'Eric', 'age':28}; y = {'age':29, 'hobby':['sport', 'travel']}")
# output: 0.31891608238220215

# 2 使用 dict() 函数的字典参数
timeit.timeit("z = dict(x, **y)", "x = {'name':'Eric', 'age':28}; y = {'age':29, 'hobby':['sport', 'travel']}")
# output: 0.30063605308532715

# 3 items 变换
timeit.timeit("z = dict(x.items() + y.items())", "x = {'name':'Eric', 'age':28}; y = {'age':29, 'hobby':['sport', 'travel']}")
# output: 0.8453028202056885

# 4 lambda 表达式
timeit.timeit("(lambda a, b: (lambda a_copy: a_copy.update(b) or a_copy)(a.copy()))(x, y)", "x = {'name':'Eric', 'age':28}; y = {'age':29, 'hobby':['sport', 'travel']}")
# output: 0.6631548404693604

结果显示,方法1和2效率最高,且两者运行时间差不多。其次是方法4,最差的是方法3。(对运行时间的计算,多次运行取平均值会更准确一点。)

总结下来,运行效率用公式表示如下:
1 = 2 > 4 > 3

标签: python

添加新评论