如何在Python中对字典内嵌套字典的price值求和 统计购物清单总金额
嵌套字典price字段累加计算购物总金额实现方案
数据结构说明
你给出的购物清单数据结构参考如下:
shopping_list = { "product1": { "product_name": "milk", "quantity": 1, "price": 2}, "product2": { "product_name": "butter", "quantity": 1, "price": 3} }
实现代码
场景1:仅累加所有商品的price字段原值
直接遍历外层字典的所有值(即每个商品的嵌套字典),提取price字段累加即可:
total_price = sum(item["price"] for item in shopping_list.values()) # 示例数据计算结果为 2 + 3 = 5 print(total_price)
场景2:计算实际应付总金额(price × 购买数量quantity)
日常使用更推荐这个逻辑,适配商品购买多份的场景:
total_amount = sum(item["price"] * item["quantity"] for item in shopping_list.values()) # 示例数据计算结果为 2*1 + 3*1 =5 print(total_amount)
容错版实现(避免缺失字段报错)
如果不确定所有商品都有price或quantity字段,可以用get方法设置默认值为0,避免抛出KeyError:
total_amount = sum( item.get("price", 0) * item.get("quantity", 0) for item in shopping_list.values() )
内容的提问来源于stack exchange,提问作者Domi
相关产品推荐
相关产品推荐

