簡體   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