Find the total sum of a list of dicts

Viewed 66

I have a list that consists of a lot of dictionaries that look like this (I inserted just the first two):

[
    {
        "_id": "60ca15162a42482a5fc83bcc",
        "name": "Fanta",
        "category": "Soft Drinks",
        "description": "Fresh Drink",
        "price": 14,
        "quantity": 104
    },
    {
        "_id": "60ca15162a42482a5fc83bcc",
        "name": "Fanta",
        "category": "Soft Drinks",
        "description": "Fresh Drink",
        "price": 16,
        "quantity": 104
    } ]

I want to get the total price. The total price looks would be like this.

total=(14*104)+(16*104)

How do I do that when I have a lot of those dictionaries inside of a list? Any thoughts?

2 Answers

You can use sum():

lst = [
    {
        "_id": "60ca15162a42482a5fc83bcc",
        "name": "Fanta",
        "category": "Soft Drinks",
        "description": "Fresh Drink",
        "price": 14,
        "quantity": 104,
    },
    {
        "_id": "60ca15162a42482a5fc83bcc",
        "name": "Fanta",
        "category": "Soft Drinks",
        "description": "Fresh Drink",
        "price": 16,
        "quantity": 104,
    },
]

total = sum(d["price"] * d["quantity"] for d in lst)
print(total)

Prints:

3120

EDIT: To create a list with totals:

total = [d["price"] * d["quantity"] for d in lst]
print(total)

Prints:

[1456, 1664]

sum(map(lambda x: x['price']*x['quantity'], lst)) should do the job

Related