[Python] Summing instead of overriding values in dictionary comprehension

Discussão em 'Python' iniciado por Stack, Junho 28, 2025.

  1. Stack

    Stack Membro Participativo

    When the keys in a dictionary comprehension is the same, I want their values to be added up. For example,

    >>> dct = {-1: 1, 0: 2, 1: 3}
    >>> {k**2: v for k, v in dct.items()}
    {1: 3, 0: 2}


    However, what I want to get in this case is {1: 4, 0: 2}, because both the square of 1 and -1 is 1, and 1 + 3 = 4.

    Clearly, I can do it with a for loop, but is there a shorthand?

    Continue reading...

Compartilhe esta Página