合并n-dictionaries和在2.6上添加值的最快方法

时间:2013-04-23 12:46:06

标签: python python-2.6

我有一个字典列表,我想将它们组合成一个字典,并添加列表中每个字典的值。例如:

ds = [{1: 1, 2: 0, 3: 0}, {1: 2, 2: 1, 3: 0}, {1: 3, 2: 2, 3: 1, 4: 5}]

最终结果应该是一个字典:

merged = {1: 6, 2: 3, 3: 1, 4: 5}

我对性能很感兴趣,我正在寻找能够将n-dictionaries列表合并到一个字典中并对值进行求和的最快实现。一个明显的实现是:

from collections import defaultdict

merged = defaultdict(int)

for d in ds:
    for k, v in d.items():
        merged[k] += v

在Python 2.6中有更快的方法吗?

1 个答案:

答案 0 :(得分:6)

defaultdict仍然是最快的,我找到了一些通过缓存函数名来加速它的方法,现在只是通过迭代for k in d而不是使用{{来找到另一种显着加速它的方法1}}或d.items()

到目前为止的一些时间:

d.iteritems()

from random import randrange
ds = [dict((randrange(1, 1000), randrange(1, 1000)) for i in xrange(500))
      for i in xrange(10000)]

# 10000 dictionaries of approx. length 500

from collections import defaultdict

def merge1(dicts, defaultdict=defaultdict, int=int):
    merged = defaultdict(int)
    for d in dicts:
        for k in d:
            merged[k] += d[k]
    return merged

def merge2(dicts):
    merged = {}
    merged_get = merged.get
    for d in dicts:
        for k in d:
            merged[k] = merged_get(k, 0) + d[k]
    return merged


def merge3(dicts):
    merged = {}
    for d in dicts:
        for k in d:
            merged[k] = merged[k] + d[k] if k in merged else 0
    return merged


from timeit import timeit
for func in ('merge1', 'merge2', 'merge3'):
    print func, timeit(stmt='{0}(ds)'.format(func),
                       setup='from __main__ import merge1, merge2, merge3, ds',
                       number=1)