You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python列表追加字典时重复添加最后值问题求助

问题:遍历生成字典并追加到列表时,所有元素均为最后一个item的值

原始数据

# 两个lineitem数据
lineitems = [
    {'line_code': 'UU', 'product_name': 'Apple', 'product_number': 'A090','quantity': '8',  'current_cost': '198.76'},
    {'line_code': 'UU', 'product_name': 'Orange', 'product_number': 'O8U8', 'quantity': '1','current_cost': '118.64'}
]

原始代码

LineCode = res['response']['data']['GetFruitList']  # 对应上述lineitems列表

ValuesinList = []
dictionary = {}
keys = ['ShippingAddress', 'ProductNumber', 'Quantity', 'Price', 'LineCode', 'Count']

for lineitem in LineCode:
    LineCode = lineitem.get('line_code')  # 覆盖外层的LineCode变量,会导致循环异常
    ProductNumber = lineitem.get('product_number')
    Quantity = lineitem.get('quantity')

    # ShippingAddress、Price未定义,运行会报错
    values = [ShippingAddress, ProductNumber, Quantity, Price, LineCode, 'Many']
    for key, value in zip(keys, values):
        dictionary[key] = value
    print("print"+str(dictionary))
ValuesinList.append(dictionary)  # 缩进错误,仅在循环结束后追加一次
print(ValuesinList)

错误结果

[{'line_code': 'UU', 'product_name': 'Orange', 'product_number': 'O8U8', 'quantity': '1'},{'line_code': 'UU', 'product_name': 'Orange', 'product_number': 'O8U8', 'quantity': '1'}]

期望结果

[{'line_code': 'UU', 'product_name': 'Apple', 'product_number': 'A090','quantity': '8'},{'line_code': 'UU', 'product_name': 'Orange', 'product_number': 'O8U8', 'quantity': '1'}]

问题原因

  1. 字典引用重复:循环外仅创建一个dictionary可变对象,每次循环仅修改该字典的键值对,列表追加的是字典的引用而非新字典,最终所有列表元素指向同一字典,显示最后一次修改的内容。
  2. 变量覆盖:循环内用LineCode = lineitem.get('line_code')覆盖了外层的原始列表变量,会导致循环逻辑异常。
  3. 未定义变量:ShippingAddress和Price未赋值,运行时会抛出NameError。
  4. 缩进错误:ValuesinList.append(dictionary)在循环外,仅会追加最后一次修改的字典(若实际代码缩进在循环内,依然会因引用问题导致重复)。

修正方案(匹配期望结果)

直接提取需要的键值对,每次循环生成新字典并追加:

LineCode = res['response']['data']['GetFruitList']
ValuesinList = []

for lineitem in LineCode:
    # 每次循环创建新字典,提取目标键值对
    new_dict = {
        'line_code': lineitem['line_code'],
        'product_name': lineitem['product_name'],
        'product_number': lineitem['product_number'],
        'quantity': lineitem['quantity']
    }
    ValuesinList.append(new_dict)

print(ValuesinList)

运行结果

[
    {'line_code': 'UU', 'product_name': 'Apple', 'product_number': 'A090', 'quantity': '8'},
    {'line_code': 'UU', 'product_name': 'Orange', 'product_number': 'O8U8', 'quantity': '1'}
]

内容的提问来源于stack exchange,提问作者DhanyaBalakrishnan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 13:15:33