首页 > 解决方案 > (Python)从嵌套字典中的特定键中查找值总和的函数

问题描述

编辑:我收到的错误如下所示。非常非常非常感谢大家的帮助。我是 Python 新手,花了几个小时研究这个但无济于事。我非常感谢您的所有帮助。

TypeError:列表索引必须是整数或切片,而不是 str

使用下面的字典,我需要找到所有组合数量的总和(1+3+3+1+9=17)。

shopping_cart = {
    "tax": .08,
    "items": [
        {
            "title": "orange juice",
            "price": 3.99,
            "quantity": 1
        },
        {
            "title": "rice",
            "price": 1.99,
            "quantity": 3
        },
        {
            "title": "beans",
            "price": 0.99,
            "quantity": 3
        },
        {
            "title": "chili sauce",
            "price": 2.99,
            "quantity": 1
        },
        {
            "title": "chocolate",
            "price": 0.75,
            "quantity": 9
        }
    ]
}

我能想到的最好的功能如下所示,但我得到一个错误。任何帮助表示赞赏。谢谢你。

def total_number_of_items(d):
    return sum(d['items']['quantity'])

标签: pythondictionarynestedsum

解决方案


因为shopping_cart['items']是一个列表,所以您需要使用列表推导(或类似的)来提取各个数量以求和:

def total_number_of_items(d):
    return sum([item['quantity'] for item in d['items']])

print(total_number_of_items(shopping_cart))

输出

17

rextester 上的演示


推荐阅读