合并字典列表中重复SKU的数量与价格并去重
SKU重复项合并解决方案
需求说明
现有包含多个字典的totalList,每个字典含sku、title、quantity、price字段。需找出所有重复的SKU,将相同SKU的quantity累加、price求和,去除重复项后得到合并后的列表。
原始列表
totalList = [ {'sku': '222222', 'title': 'apple', 'quantity': '2', 'price': '3$'}, {'sku': '333333', 'title': 'banana', 'quantity': '1', 'price': '1.5$'}, {'sku': '444444', 'title': 'peach', 'quantity': '5', 'price': '9$'}, {'sku': '123456', 'title': 'tv', 'quantity': '1', 'price': '500$'}, {'sku': '777777', 'title': 'apple', 'quantity': '2', 'price': '3$'}, {'sku': '123456', 'title': 'tv', 'quantity': '2', 'price': '1000$'}, {'sku': '333333', 'title': 'banana', 'quantity': '4', 'price': '6$'}, ]
期望结果
totalList = [ {'sku': '222222', 'title': 'apple', 'quantity': '2', 'price': '3$'}, {'sku': '333333', 'title': 'banana', 'quantity': '5', 'price': '7.5$'}, {'sku': '444444', 'title': 'peach', 'quantity': '5', 'price': '9$'}, {'sku': '123456', 'title': 'tv', 'quantity': '3', 'price': '1500$'}, {'sku': '777777', 'title': 'apple', 'quantity': '2', 'price': '3$'}, ]
错误代码分析
当前提供的错误代码存在核心逻辑缺陷:
newList = [] for x in totalList: for y in totalList: if x['sku'] == y['sku']: x['quantity'] = int(x['quantity']) + int(y['quantity']) else: newList.append(x)
- 嵌套循环会对同一SKU的项进行多次重复累加,导致
quantity数值严重错误 - 每次循环都会将
x添加到newList,造成大量重复项,完全未实现去重目标
正确解决方案
使用字典按SKU分组处理,是效率最高的实现方式:
# 创建临时字典,以sku为键存储合并后的数据 temp_dict = {} for item in totalList: sku = item['sku'] # 提取数值部分,转换为可计算的类型 quantity = int(item['quantity']) price = float(item['price'].replace('$', '')) if sku not in temp_dict: # 首次遇到该sku,复制原字典并转换数值字段 temp_dict[sku] = item.copy() temp_dict[sku]['quantity'] = quantity temp_dict[sku]['price'] = price else: # 累加quantity和price temp_dict[sku]['quantity'] += quantity temp_dict[sku]['price'] += price # 将临时字典的值转换为列表,并恢复字符串格式 merged_list = [] for item in temp_dict.values(): # 转换quantity为字符串,price根据是否为整数决定格式 item['quantity'] = str(item['quantity']) if item['price'].is_integer(): item['price'] = f"{int(item['price'])}$" else: item['price'] = f"{item['price']}$" merged_list.append(item) # 输出结果 print(merged_list)
代码说明
- 分组存储:用
temp_dict以SKU为键,避免重复遍历,时间复杂度为O(n) - 数值处理:先去除价格的
$符号并转换为数值类型,确保计算准确 - 格式恢复:最后将计算后的数值转回原字符串格式,保持结果与原始数据结构一致
内容的提问来源于stack exchange,提问作者gozom
相关产品推荐
相关产品推荐

