如何将含重复元素的字典列表聚合为嵌套字典?
字典列表聚合为嵌套字典的解决方案
问题描述
需要将包含重复元素的字典列表聚合为指定结构的嵌套字典:
原始列表
list_dict = [{'id': 1, 'table': 8, 'category': 'fruit', 'product': 'banana', 'price': 4, 'qty': 5}, {'id': 1, 'table': 8, 'category': 'fruit', 'product': 'apple', 'price': 5, 'qty': 9}, {'id': 1, 'table': 8, 'category': 'fruit', 'product': 'orange', 'price': 6, 'qty': 3}, {'id': 2, 'table': 5, 'category': 'vegetable', 'product': 'carrot', 'price': 4, 'qty': 5}, {'id': 2, 'table': 5, 'category': 'vegetable', 'product': 'potato', 'price': 2, 'qty': 3}]
预期结果
[{'id': 1, 'table': 8, 'category': 'fruit', 'products': [{'product': 'banana', 'price': 4, 'qty': 5}, {'product': 'apple', 'price': 5, 'qty': 9}, {'product': 'orange', 'price': 6, 'qty': 3}]}, {'id': 2, 'table': 5, 'category': 'vegetable', 'products': [{'product': 'carrot', 'price': 4, 'qty': 5}, {'product': 'potato', 'price': 2, 'qty': 3}]}]
尝试使用itertools.groupby实现但未得到正确结果。
解决方案
itertools.groupby的核心要求是先按分组键对列表排序,否则只会将连续的同组元素聚合,非连续的会被当成不同组处理。以下是正确实现代码:
import itertools # 先按分组键(id, table, category)排序,确保同组元素连续 sorted_list = sorted(list_dict, key=lambda x: (x['id'], x['table'], x['category'])) result = [] # 按分组键进行分组 for key, group in itertools.groupby(sorted_list, key=lambda x: (x['id'], x['table'], x['category'])): id_val, table_val, category_val = key # 提取每组中的产品信息,组成products列表 products = [{'product': item['product'], 'price': item['price'], 'qty': item['qty']} for item in group] # 构建聚合后的字典并加入结果列表 result.append({ 'id': id_val, 'table': table_val, 'category': category_val, 'products': products }) print(result)
代码说明
- 排序步骤:通过
sorted()函数以(id, table, category)作为排序键,保证相同分组的元素连续排列,这是groupby正确聚合的必要前提。 - 分组处理:使用
groupby按相同的键分组,每个分组对应最终结果里的一个条目。 - 结果构建:遍历每个分组,提取公共的
id、table、category值,再将分组内的元素转换为仅包含产品相关字段的字典,最后整合成目标嵌套结构。
内容的提问来源于stack exchange,提问作者Eduardo
相关产品推荐
相关产品推荐

