我正在尝试将“项目”中的字典数量相加
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
}
]
}
答案 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)