簡體   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