Skip to main content
 首页 » 编程设计

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

2025年05月04日12emanlee

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

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

请您参考如下方法:

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

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