[Python] add results of nested dictionaries together

Discussão em 'Python' iniciado por Stack, Maio 19, 2025.

  1. Stack

    Stack Membro Participativo

    Is there a more efficient way to sum the keys of a subdictionary than the following?

    for house in my_dictionary:
    artifact['Total']['Count'] += artifact['A']['Count']
    artifact['Total']['Action'] += artifact['B']['Action']
    artifact['Total']['Passive'] += artifact['C']['Passive']


    I feel like there is a way to condense this, but I can't figure it out. I've written what is happening out in question form below. I came up with an answer, but I think that there is a better one out there.

    If I have the following dictionary my_dictionary:

    {
    "A": {
    "Count": 3,
    "Action": 3,
    "Passive": 0
    },
    "B": {
    "Count": 1,
    "Action": 0,
    "Passive": 1
    },
    "C": {
    "Count": 1,
    "Action": 1,
    "Passive": 0
    },
    "Total": {
    "Count": 0,
    "Action": 0,
    "Passive": 0
    }


    Once the my_dictionary has been created (with everything in Total blank), I to populate Total where Total is a sum of each of the other fields respective keys?

    {
    "A": {
    "Count": 3,
    "Action": 3,
    "Passive": 0
    },
    "B": {
    "Count": 1,
    "Action": 0,
    "Passive": 1
    },
    "C": {
    "Count": 1,
    "Action": 1,
    "Passive": 0
    },
    "Total": {
    "Count": 5,
    "Action": 4,
    "Passive": 1
    }

    Continue reading...

Compartilhe esta Página