如何合并Python字典列表中重复日期的对应数值?
解决方案
这里提供几种实用的方法来实现按日期分组求和的需求:
方法一:使用普通字典手动分组累加
先遍历原列表,用日期作为键维护每个日期对应的数值总和,最后将字典转换为目标格式的列表:
foo = [{'date':'01-08-2022', 'pre_val':90, 'cur_val':100},{'date':'02-08-2022', 'pre_val':70, 'cur_val':100},{'date':'01-08-2022', 'pre_val':60, 'cur_val':50}] # 初始化字典存储每个日期的累加值 sum_dict = {} for item in foo: date = item['date'] if date not in sum_dict: # 首次遇到该日期,初始化数值 sum_dict[date] = {'date': date, 'pre_val': item['pre_val'], 'cur_val': item['cur_val']} else: # 已存在该日期,累加对应数值 sum_dict[date]['pre_val'] += item['pre_val'] sum_dict[date]['cur_val'] += item['cur_val'] # 将字典的值转换为列表,得到结果 bar = list(sum_dict.values()) print(bar)
方法二:使用collections.defaultdict简化代码
借助defaultdict省去判断日期是否存在的步骤,让代码更简洁:
from collections import defaultdict foo = [{'date':'01-08-2022', 'pre_val':90, 'cur_val':100},{'date':'02-08-2022', 'pre_val':70, 'cur_val':100},{'date':'01-08-2022', 'pre_val':60, 'cur_val':50}] sum_dict = defaultdict(lambda: {'pre_val': 0, 'cur_val': 0}) for item in foo: date = item['date'] sum_dict[date]['pre_val'] += item['pre_val'] sum_dict[date]['cur_val'] += item['cur_val'] # 转换为目标列表格式 bar = [{'date': k, **v} for k, v in sum_dict.items()] print(bar)
方法三:使用Pandas快速处理(适合大规模数据)
如果数据量较大,用Pandas的分组聚合功能会更高效:
import pandas as pd foo = [{'date':'01-08-2022', 'pre_val':90, 'cur_val':100},{'date':'02-08-2022', 'pre_val':70, 'cur_val':100},{'date':'01-08-2022', 'pre_val':60, 'cur_val':50}] # 转换为DataFrame df = pd.DataFrame(foo) # 按date分组,对pre_val和cur_val求和 grouped_df = df.groupby('date', as_index=False).sum() # 转换为字典列表 bar = grouped_df.to_dict('records') print(bar)
以上三种方法都能得到你需要的结果,可根据实际场景选择合适的方案。
内容的提问来源于stack exchange,提问作者Deekshith Hari
相关产品推荐
相关产品推荐

