繁体   English   中英

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

[英](Python) Function to find sum of values from specific key in nested dictionary

编辑:我收到的错误如下所示。 非常、非常、非常感谢你们的帮助。 我是 Python 的新手,花了几个小时研究这个无济于事。 我真的很感谢你的帮助。

类型错误:列表索引必须是整数或切片,而不是 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'])

因为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

雷克斯特演示

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

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

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 的新手,可能还不熟悉它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM