在字典Python中汇总列表

时间:2019-08-15 20:02:59

标签: python

我正在尝试将“项目”中的字典数量相加

receipt = {
  "tax": .06,
  "items": [
    {
        "food": "grapes",
        "price": 2.50,
        "quantity": 1
    },
    {
        "food": "apples",
        "price": 1.99,
        "quantity": 3
    },
    {
        "food": "peach",
        "price": 0.99,
        "quantity": 3
    }

  ]
}

2 个答案:

答案 0 :(得分:0)

价格:

total = 0
for each in receipt['items']:
    total = total + each['price']
print(total)

对于数量:

total = 0
for each in receipt['items']:
     total = total + each['quantity']
print(total)

答案 1 :(得分:0)

遍历items,对于每个item,获得quantity并添加到total

receipt = {
  "tax": .06,
  "items": [
    {
        "food": "grapes",
        "price": 2.50,
        "quantity": 1
    },
    {
        "food": "apples",
        "price": 1.99,
        "quantity": 3
    },
    {
        "food": "peach",
        "price": 0.99,
        "quantity": 3
    }

  ]
}
total = 0
for item in receipt["items"]:
     total += item["quantity"]
print(total)