下面我有一个嵌套字典列表,其中包括给定汽车品牌/型号/年份的汽车销售
cars =
[{'id': 2, 'car':
{'car_make':'Acura', 'car_model':'TL', 'car_year':2005},'total_sales':589},
{'id': 30, 'car':
{'car_make':'Acura', 'car_model':'TL', 'car_year':2004}, 'total_sales':167},
{'id': 31, 'car':
{'car_make':'Acura', 'car_model':'Integra', 'car_year':2008}, 'total_sales':200},
{'id': 71, 'car':
{'car_make':'BMW', 'car_model':'5 Series', 'car_year':2011},'total_sales':824},
{'id': 72, 'car':
{'car_make':'BMW', 'car_model':'5 Series', 'car_year':2001}, 'total_sales':6}]
我想计算所有年份的总销售额,并返回一本包含汽车品牌、型号和总销售额的总销售额字典
total_sales = {{'car_make': 'Acura', 'car_model': 'TL', 'total_sales': 756},
{'car_make': 'Acura', 'car_model': 'Integra', 'total_sales': 200},
{'car_make': 'BMW', 'car_model': '5 Series', 'total_sales': 830}}
下面是我的代码,我在其中迭代嵌套的字典,并添加销售总额
total_sales = {'car_make':{}}
for car in cars:
if car['car']['car_make'] in total_sales['car_make'] and car['car']['car_model'] in
total_sales['car_model']:
total_sales['total_sales'] = total_sales['total_sales'] + car['total_sales']
else:
total_sales['car_make'] = car['car']['car_make']
total_sales['car_model'] = car['car']['car_model']
total_sales['total_sales'] = car['total_sales']
print(total_sales)
然而,我得到的是每一个汽车品牌和车型的总销量,而不是最终的总销量
{'car_make': 'Acura', 'car_model': 'TL', 'total_sales': 589}
{'car_make': 'Acura', 'car_model': 'TL', 'total_sales': 756}
{'car_make': 'Acura', 'car_model': 'Integra', 'total_sales': 200}
{'car_make': 'BMW', 'car_model': '5 Series', 'total_sales': 824}
{'car_make': 'BMW', 'car_model': '5 Series', 'total_sales': 830}
我是python新手,如果有人能解释我做错了什么,我将不胜感激。我还研究了其他主题,包括迭代嵌套字典,但似乎没有什么适合我的情况
您可以使用
collections.defaultdict
:输出:
根据你的字典变得有多疯狂,以及你想获得这种类型的统计信息的粒度,你可能想研究重构你的结构,以使用
pandas
,这为数据操作、切片打开了更多的大门,然而对于初学者来说,它确实有一点学习曲线,所以我将避免通常的建议“嘿,使用这个库”。如果您感兴趣,可以阅读一些文档,https://pandas.pydata.org/docs/要直接回答您的问题,您可能需要重新构建total sales字典。您可以使用一个“total_sales_by_make_and_model”字典,然后使用
cars
列表中列出的make键作为该字典的键--这会使它更清晰一些,但是我不确定这与您的整体“业务”逻辑有什么关系我还建议将代码扩展一点,以将键名存储在变量中,至少在看到求和出错的地方之前是这样
此结果将使您能够灵活地在make键中按模型进行查询。例如:
输出:
如果您想获得每个品牌的总销售额,可以使用一个简单的循环遍历每个键并对值求和:
输出:
编辑:必须修复几个给出错误金额的主要打字错误:)
以下是一种方法:
输出
相关问题 更多 >
编程相关推荐