如何对字典列表中相同key的value值求和合并?
实现字典列表中相同key的value值求和
实现思路
借助一个临时字典记录每个key对应的累计value值,遍历原列表完成累加后,再将临时字典转换为目标格式的字典列表。
代码实现
# 原字典列表 original_list = [{'key': '', 'value': 494}, {'key': 'cloud', 'value': 63}, {'key': 'cloud', 'value': 44}] # 初始化临时字典用于累加value sum_dict = {} for item in original_list: current_key = item['key'] current_value = item['value'] # 存在对应key则累加value,不存在则初始化 if current_key in sum_dict: sum_dict[current_key] += current_value else: sum_dict[current_key] = current_value # 转换为目标格式的字典列表 result = [{'key': k, 'value': v} for k, v in sum_dict.items()] print(result)
运行结果
[{'key': '', 'value': 494}, {'key': 'cloud', 'value': 107}]
内容的提问来源于stack exchange,提问作者JohnDole
相关产品推荐
相关产品推荐

