(Python)从嵌套字典中的特定键中查找值总和的函数

时间:2020-03-14 03:47:31

标签: python dictionary nested sum

编辑:我收到的错误如下所示。非常非常非常感谢您的帮助。我是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'])

3 个答案:

答案 0 :(得分:2)

由于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

spread syntax

答案 1 :(得分:0)

def tot(d):    
    print(sum([i['quantity'] for i in d['items']]))

答案 2 :(得分:-1)

我可以给你一个直接的答案:

In [42]: functools.reduce(lambda i, j: i+j["quantity"], shopping_cart["items"], 0)                                                                                                                                                                           
Out[42]: 17

但是您需要非常清楚地知道问题和所面临的错误。请遵循社区和StackOverflow准则https://stackoverflow.com/help/how-to-ask,我发现您是Stackoverflow的新手,可能还不了解。

相关问题