繁体   English   中英

将字典列表合并到单个字典中,为公共键添加值

[英]Merge a list of dicts into a single dict adding values for common keys

我怎样才能打开这样的字典列表

dico = [{'a':1}, {'b':2}, {'c':1}, {'d':2}, {'e':2}, {'d':3}, {'g':1}, {'h':4}, {'h':2}, {'f':6}, {'a':2}, {'b':2}]

像这样进入一个单一的字典

{'a':3, 'b':4, 'c':1, 'd':5,'e':2,'f':6 , 'g':1 ,'h':6}

在执行此操作的那一刻

result = {}
for d in dico:
  result.update(d)
print(result)

结果:

{'a': 2, 'b': 2, 'c': 1, 'd': 3, 'e': 2, 'g': 1, 'h': 2, 'f': 6}

只需将您的字典替换为collections.Counter

from collections import Counter

dico = [{'a':1}, {'b':2}, {'c':1}, {'d':2}, {'e':2}, {'d':3}, {'g':1}, {'h':4}, {'h':2}, {'f':6}, {'a':2}, {'b':2}]

result = Counter()
for d in dico:
    result.update(d)
print(result)

Output:

Counter({'h': 6, 'f': 6, 'd': 5, 'b': 4, 'a': 3, 'e': 2, 'c': 1, 'g': 1})

为什么上述内容适用于文档中的Counter update

元素是从另一个映射(或计数器)的可迭代或附加项中计算出来的。 dict.update()但添加计数而不是替换它们。 此外,iterable 应该是一个元素序列,而不是 (key, value) 对的序列。

这是使用collections.Counter的一种奇特方法,它是一种字典:

from collections import Counter

def add_dicts(dicts):
    return sum(map(Counter, dicts), Counter())

以上对于大量字典来说效率不高,因为它为结果创建了许多中间Counter对象,而不是就地更新一个结果,因此它以二次时间运行。 这是一个类似的解决方案,它在线性时间内运行:

from collections import Counter

def add_dicts(dicts):
    out = Counter()
    for d in dicts:
        out += d
    return out

使用defaultdict

from collections import defaultdict
dct = defaultdict(int)

for element in dico:
    for key, value in element.items():
        dct[key] += value

print(dct)

哪个产量

defaultdict(<class 'int'>, 
    {'a': 3, 'b': 4, 'c': 1, 'd': 5, 'e': 2, 'g': 1, 'h': 6, 'f': 6})


至于时间测量,这是四个答案之间的比较:

0.839742998
0.8093687279999999
0.18643740100000006
0.04764247300000002

在我的MacBookAir上,这会产生

0.839742998 0.8093687279999999 0.18643740100000006 0.04764247300000002

因此,使用默认 dict 的解决方案是迄今为止最快的(因子 15-20),其次是 @RoadRunner。

使用collections.Countersum

from collections import Counter

dico = [{'a':1}, {'b':2}, {'c':1}, {'d':2}, {'e':2}, {'d':3}, {'g':1}, {'h':4}, {'h':2}, {'f':6}, {'a':2}, {'b':2}]


result = sum((Counter(e) for e in dico), Counter())
print(result)

Output

Counter({'h': 6, 'f': 6, 'd': 5, 'b': 4, 'a': 3, 'e': 2, 'c': 1, 'g': 1})

如果您需要严格的字典,请执行以下操作:

result = dict(sum((Counter(e) for e in dico), Counter()))
print(result)

您可以修改您的方法,如下所示:

result = {}
for d in dico:
    for key, value in d.items():
        result[key] = result.get(key, 0) + value

print(result)

update方法将替换文档中现有键的值:

使用其他键/值对更新字典,覆盖现有键。

import collections

counter = collections.Counter()

for d in dico:
    counter.update(d)

result = dict(counter)
print(result)

Output

{'a': 3, 'b': 4, 'c': 1, 'd': 5, 'e': 2, 'g': 1, 'h': 6, 'f': 6}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM