gpt4 book ai didi

python - 如果键存在于字典列表中,则获取值

转载 作者:太空宇宙 更新时间:2023-11-04 07:14:45 25 4
gpt4 key购买 nike

我有一个类似 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

如何检查 imonth 是否存在并获取字典?

最佳答案

您可以将您的字典列表转换为直接月份:与

的总映射
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)]

关于python - 如果键存在于字典列表中,则获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52136547/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com