Sum the total values of each key of the Python dictionaries

Asked

Viewed 92 times

-2

I have the following list of Python dictionaries :

creches = [
    {
        "nome": "Recanto do Sol",
        "cachorros": 12,
        "gatos": 4,
        "coelhos": 2,
    },
    {
        "nome": "Lar dos bichos",
        "cachorros": 8,
        "gatos": 5,
        "porquinhos-da-índia": 3,
    },
    {
        "nome" : "A Fazenda",
        "cachorros": 20,
        "coelhos": 10,
    },
    {
        "nome": "Casa da alegria",
        "gatos": 15,
        "porquinhos-da-índia": 7,
    },
]

I need the output to be:

quantidade_de_animais_por_especie = {
    "cachorros": 100,
    "gatos": 70,
    ...
} 

1 answer

1

Just create a totally empty dictionary to store the sums and go through each animal from each daycare - checking if the key is different from "nome". That way, you can compute the amount of unlimited species of animals without having to modify anything in the code.

Below is a simple function to perform this task:

def obter_quantidade_de_animais(registro, excluir = ()):

    resultado = {}
    
    for creche in registro:
        for key in creche:
            if not key in excluir:
                resultado[key] = resultado.get(key, 0) + creche[key]

    return resultado

Note that the function has a parameter called excluir. Through this parameter, you can add keys to be ignored when computing the data, as in the example below, where the key "nome" is ignored by counting the other key data - in this case, animals.

resultado = obter_quantidade_de_animais(creches, ("nome", ))
# {'cachorros': 40, 'gatos': 24, 'coelhos': 12, 'porquinhos-da-índia': 10}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.