9

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

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 字典列表合并到一个字典中并对值求和的最快实现。一个明显的实现是:

from collections import defaultdict

merged = defaultdict(int)

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

在 Python 2.6 中有没有更快的方法来做到这一点?

4

1 回答 1

6

defaultdict仍然是最快的,我找到了一些通过缓存函数名称来加速它的方法,现在刚刚找到了另一种显着加快速度的方法,只需迭代for k in d而不是使用d.items()ord.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)

merge1 0.992541510164
merge2 1.40478747997
merge3 1.23502204889
于 2013-04-23T12:48:36.123 回答