简体   繁体   中英

How to merge and sum dictionary values in Python

I'd like to sum up all values in multiple Python dictionaries with the same key and keep the other values as is if they have a different key. The input dictionaries would look something like this:

dict1 = {'A':{'a':1, 'b':2, 'c':0}, 'B':{'a':3, 'b':0, 'c':0}}
dict2 = {'A':{'a':3, 'c':1, 'd':5}, 'B':{'a':2, 'b':0, 'c':1}, 'C':{'a':1, 'b':2, 'c':1}}

Output:

dict3 = {'A':{'a':4, 'b':2, 'c':1, 'd':5}, 'B':{'a':5, 'b':0, 'c':1}, 'C':{'a':1, 'b':2, 'c':1}}

Is there any way to achieve this result using only the standard library? This should also work with more than 2 dictionaries.

Very structure dependent, however something like...

dicts = [
    {'A':{'a':1, 'b':2, 'c':0}, 'B':{'a':3, 'b':0, 'c':0}},
    {'A':{'a':3, 'c':1, 'd':5}, 'B':{'a':2, 'b':0, 'c':1}, 'C':{'a':1, 'b':2, 'c':1}}
]

odict = {}
for d in dicts:
    for dk in d.keys():
        if dk not in odict:
            odict[dk] = {}
        for inner_dk in d[dk].keys():
            if inner_dk not in odict[dk]:
                odict[dk][inner_dk] = d[dk][inner_dk]
            else:
                odict[dk][inner_dk] += d[dk][inner_dk]

print(odict)

A function that accepts multiple dicts:

dict1 = {"A": {"a": 1, "b": 2, "c": 0}, "B": {"a": 3, "b": 0, "c": 0}}
dict2 = {
    "A": {"a": 3, "c": 1, "d": 5},
    "B": {"a": 2, "b": 0, "c": 1},
    "C": {"a": 1, "b": 2, "c": 1},
}


def merge_dicts(*dicts):
    if not dicts:
        return

    out = {}
    all_keys = set(dicts[0]).union(k for d in dicts[1:] for k in d)

    for k in all_keys:
        out[k] = {}
        for kk in set(dicts[0].get(k, {})).union(
            k_ for d in dicts[1:] for k_ in d.get(k, {})
        ):
            out[k][kk] = sum(d.get(k, {}).get(kk, 0) for d in dicts)

    return out


print(merge_dicts(dict1, dict2))

Prints:

{'C': {'c': 1, 'a': 1, 'b': 2}, 'A': {'c': 1, 'd': 5, 'a': 4, 'b': 2}, 'B': {'c': 1, 'a': 5, 'b': 0}}

For input:

dict1 = {"A": {"a": 1, "b": 2, "c": 0}, "B": {"a": 3, "b": 0, "c": 0}}
dict2 = {
    "A": {"a": 3, "c": 1, "d": 5},
    "B": {"a": 2, "b": 0, "c": 1},
    "C": {"a": 1, "b": 2, "c": 1},
}
dict3 = {
    "A": {"a": 100},
}


print(merge_dicts(dict1, dict2, dict3))

Prints:

{'A': {'a': 104, 'b': 2, 'c': 1, 'd': 5}, 'B': {'a': 5, 'b': 0, 'c': 1}, 'C': {'a': 1, 'b': 2, 'c': 1}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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