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

为何Woocommerce API属性更新生成字典元组而非字典列表?

问题分析:为什么生成的是字典元组而非列表?

原始输入数据

[{'id': 14786,
  'sku': '0663370-ZWA',
  'sizes': ['38', '40', '42', '44', '46'],
  'color': 'zwart'},
 {'id': 14787,
  'sku': '0663371-ZWA',
  'sizes': ['38', '40', '42', '44', '46'],
  'color': 'zwart'}]

问题代码

list_of_update_items = []

for index in lst_of_dcts:
    lst_of_attributes_items=[]
    attributes = {'id': 1, 'name': 'kleur', 'position': 0,'options': index['color'], 'variations': 'false','visible': 'true'},{'id': 6, 'options': index['sizes'], 'variations': 'true','visible': 'true'} 
    # make a list of attributes_items to use as value in the parent dict 
    lst_of_attributes_items.append(attributes)
    #make a dict with id as key and atribute_list as key
    update = {'id': index['id'], 'attributes': lst_of_attributes_items}
    list_of_update_items.append(update)
    #clear the list of attributes_items for the next iteration
    lst_of_attributes_items=[]
    #wrap in the top_dict
    data = {'update': list_of_update_items}

错误输出结果

{'update': [{'id': 14786,
   'attributes': [({'id': 1,
      'name': 'kleur',
      'position': 0,
      'options': 'zwart',
      'variations': 'false',
      'visible': 'true'},
     {'id': 6,
      'options': ['38', '40', '42', '44', '46'],
      'variations': 'true',
      'visible': 'true'})]},
  {'id': 14787,
   'attributes': [({'id': 1,
      'name': 'kleur',
      'position': 0,
      'options': 'zwart',
      'variations': 'false',
      'visible': 'true'},
     {'id': 6,
      'options': ['38', '40', '42', '44', '46'],
      'variations': 'true',
      'visible': 'true'})]}]}

原因分析

问题出在attributes变量的定义上:你用逗号分隔两个字典但没有用方括号[]包裹,在Python中,用逗号分隔的多个元素会被自动识别为元组(即使没有圆括号),所以attributes实际是一个包含两个字典的元组,而不是列表。之后你把这个元组添加到lst_of_attributes_items列表里,就导致attributes字段的值变成了[元组]的结构。

修复方案

把attributes的定义改成用方括号包裹的列表即可,同时可以简化代码逻辑:

list_of_update_items = []

for item in lst_of_dcts:
    # 直接用方括号创建属性列表
    attributes = [
        {'id': 1, 'name': 'kleur', 'position': 0, 'options': item['color'], 'variations': 'false', 'visible': 'true'},
        {'id': 6, 'options': item['sizes'], 'variations': 'true', 'visible': 'true'}
    ]
    # 直接将属性列表赋值给attributes字段
    update = {'id': item['id'], 'attributes': attributes}
    list_of_update_items.append(update)

data = {'update': list_of_update_items}

修复后,attributes字段的值会变成包含两个字典的列表,符合Woocommerce API的要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 22:45:28