作者:好运娟_968 | 来源:互联网 | 2022-12-05 20:30
我有一个python列表
[{'month': 8, 'total': 31600.0}, {'month': 9, 'total': 2000.0}]
并希望像它一样生成它
[
{'month': 1, 'total': 0},
{'month': 2, 'total': 0},
...
{'month': 8, 'total': 31600},
{'month': 9, 'total': 2000},
...
{'month': 12, 'total': 0}
]
为此,我正在对范围进行迭代 (1,13)
new_list = []
for i in range(1, 13):
# if i exists in month, append to new_list
# else add total: 0 and append to new_list
我如何检查是否我的存在一个月,并得到字典?
1> taras..:
您可以将您的dict列表转换为直接月份:总映射
monthly_totals = {item['month']: item['total'] for item in data_list}
并使用简单的列表理解dict.get
来处理缺失值:
new_list = [{'month': i, 'total': monthly_totals.get(i, 0)} for i in range(1, 13)]