[Python] How to sum values across dicts? [duplicate]

Discussão em 'Python' iniciado por Stack, Abril 18, 2025.

  1. Stack

    Stack Membro Participativo

    I'm using python 3.7. I have a list of dicts that and I want to create a concatenated dict where that concatenated dicts sums over values (grouped by keys) per key in the initial list of dicts.

    So e.g.,

    d1 = {1: 1.1, 2: 2.2}
    d2 = {1: 3.3, 4: 5.5}


    The result should be:

    final_dict = {1: 4.4, 2: 2.2, 4: 5.5}


    I tried to do dict([*d1.items(), *d2.items()]) but this overwrites duplicate keys instead of summing them.

    Currently, I just do

    def _sum_dicts_by_key(dicts):
    result = defaultdict(float)
    for d in dicts:
    for k, v in d.items():
    result[k] += v


    but I feel there should be a pythonic way to do it without explicitly looping?

    Continue reading...

Compartilhe esta Página