簡體   English   中英

如何在Python中組合多個字典,求和公共鍵的值(並保留值為0的鍵)?

[英]How to combine multiple dicts, summing the values of common keys (and retaining those with value 0) in Python?

給定三個命令d1,d2和d3:

d1

{'a':1,'b':2,'c':3, 'd':0)

d2

{'b':76}

3天

{'a': 45, 'c':0}

多個字典共有一些鍵名(實際上,它們代表相同的現實對象)。 其他諸如d1中的“ d”僅存在於d2中。 我想將所有字典分組在一起, 首先首先求和公用鍵的值,最后得到:

{'a':46, 'b':78, 'c':3, 'd': 0}

如果每個dict大小相同且包含相同的鍵,則可以執行以下操作:

summedAndCombined = {}
    for k,v in d1.items():
        summedAndCombined[k] = d1[k]+d2[k]+d3[k]

但這會在到達d1中的鍵(而不是其他鍵)時分解。 我們如何實現這一目標?

更新

不能重復。 collections.Counter 幾乎可以工作,但是如果鍵d的值為零(高於該值),則生成的Counter中將缺少鍵d。

In [128]: d1 = {'a':1,'b':2,'c':3, 'd':0}

In [129]: d2 = {'b':76}

In [130]: d3 = {'a': 45, 'c':0}

In [131]: from collections import Counter

In [132]: Counter(d1) + Counter(d2) + Counter(d3)
Out[132]: Counter({'b': 78, 'a': 46, 'c': 3})

如果您希望0鍵持續存在,可以使用update而不是+Counter配合使用:

>>> c = Counter()
>>> for d in d1, d2, d3:
...     c.update(d)
...     
>>> c
Counter({'b': 78, 'a': 46, 'c': 3, 'd': 0})

(這可能是一個dup,但是我現在找不到。)

未測試:

def merge_dicts(*dicts):
    res = {}
    for key in set(sum(map(list, dicts), [])):
        res[key] = 0
        for dct in dicts:
            res[key] += dct.get(key, 0)
    return res

用法示例:

merge_dicts(d1, d2, d3)

collections.defaultdict進行救援

import collections
d = collections.defaultdict(int)
for thing in [d1, d2, d3]:
    for k, v in thing.items():
        d[k] += v

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM