首页 > 解决方案 > 查找字典列表的总和

问题描述

我有一个列表,其中包含很多看起来像这样的字典(我只插入了前两个):

[
    {
        "_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=(14*104)+(16*104)

当列表中有很多字典时,我该怎么做?有什么想法吗?

标签: pythonlistdictionary

解决方案


您可以使用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)

印刷:

3120

编辑:要创建一个总计列表:

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

印刷:

[1456, 1664]

推荐阅读