Python遍历非存在索引报错:如何按attribute_id提取属性名称?
问题背景
从WooCommerce API提取的商品数据结构示例:
{'id': 12345, 'attributes': [{'id': 1, 'name': 'kleur', 'position': 0, 'visible': True, 'variation': False, 'options': ['blauw']}, {'id': 2, 'name': 'maat', 'position': 1, 'visible': True, 'variation': True, 'options': ['s', 'm', 'l']}], # 其他字段省略 }
原尝试构建字典列表的代码:
all_webshop_skus = [] for item in all_data: product= {} product = { 'id':item['id'], 'sku': item['sku'], 'name' : item['name'], 'date_created': item['date_created'], 'brands': item['brands'][0]['name'], 'attributes': item['attributes'][1]['name'] } all_webshop_skus.append(product)
执行时抛出的错误:
---> 16 'attributes': item['attributes'][1]['name'] 17 } 18 all_webshop_skus.append(product) IndexError: list index out of range
问题核心:并非所有商品的attributes列表都包含第二个元素(索引1),需改为通过attribute_id=2匹配属性,而非依赖固定索引。
解决方案
使用生成器表达式遍历属性列表,精准匹配id=2的属性项,同时处理属性不存在的情况避免报错:
all_webshop_skus = [] for item in all_data: # 查找id为2的属性,无匹配项则返回None target_attribute = next((attr for attr in item['attributes'] if attr['id'] == 2), None) # 提取属性名称,无匹配项时设为None(可根据需求改为空字符串等默认值) attribute_name = target_attribute['name'] if target_attribute else None product = { 'id': item['id'], 'sku': item['sku'], 'name': item['name'], 'date_created': item['date_created'], 'brands': item['brands'][0]['name'], 'attributes': attribute_name } all_webshop_skus.append(product)
代码说明
next()函数会返回生成器中第一个匹配attr['id'] == 2的元素,无匹配项时返回None,避免索引越界- 三元表达式处理属性不存在的场景,防止抛出KeyError或AttributeError
- 该方法不依赖属性在列表中的排列位置,只要存在
id=2的属性就能正确提取,兼容性更强
内容的提问来源于stack exchange,提问作者Ron Kieftenbeld
相关产品推荐
相关产品推荐

