python - (Python)从嵌套字典中的特定键中查找值总和的函数
问题描述
编辑:我收到的错误如下所示。非常非常非常感谢大家的帮助。我是 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'])
解决方案
因为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
推荐阅读
- javascript - HtmlUnit WebClient.getPage 不处理 javascript
- compiler-construction - 首先计算并遵循此语法的集合
- azure-devops - 源提供者 - 列出分支 - 什么是 providerName?
- matlab - 如何找到给定维度中 3D 矩阵的最小值?
- c++ - 如何使用 range-v3 库从 std::vector 获取列视图和行视图?
- c - 为什么可以在 C 中生成动态大小的数组?
- python - 如何使用Python将各个数字的索引存储在单独数组中的列表中
- java - Kafka Consumer架构设计:java插件或外部客户端
- dynamics-crm - CRM 操作中的可选输入参数在代码活动中始终为 NULL,即使未通过?
- powershell - 用户通过 powershell 脚本插入后 CN 中的“\”字符