如何从API返回的嵌套字典中提取含attributeId的属性数据
实现API返回数据筛选的操作方法
核心逻辑为遍历外层字典时,对attributes数组做二次判断,检查数组内的字典是否包含attributeId键即可完成筛选,以下为Python环境下的实现示例:
参考数据结构
你获取到的API返回结构可参考如下样例:
api_response = [ { "type": "item", "id": "1001", "description": "测试条目1", "attributes": [ {"attributeId": "attr_001", "value": "红色"}, {"name": "尺寸", "value": "XL"} ] }, { "type": "item", "id": "1002", "description": "测试条目2", "attributes": [ {"attributeId": "attr_002", "value": "蓝色"}, {"attributeId": "attr_003", "value": "纯棉"} ] }, { "type": "item", "id": "1003", "description": "测试条目3", "attributes": [ {"name": "重量", "value": "200g"} ] } ]
两种常见筛选场景的实现
1. 筛选外层条目:只要attributes数组中至少存在一个带attributeId的属性,就保留整个外层字典
使用列表推导式即可快速实现:
filtered_items = [ item for item in api_response if any("attributeId" in attr for attr in item["attributes"]) ]
遍历打印筛选后内容的示例:
for item in filtered_items: print(f"类型:{item['type']}, ID:{item['id']}, 描述:{item['description']}") # 可选:单独打印该条目中带attributeId的属性 valid_attrs = [attr for attr in item["attributes"] if "attributeId" in attr] print(f"有效属性:{valid_attrs}")
2. 筛选attributes内部条目:保留所有外层条目,但每个条目的attributes仅留存带attributeId的字典
实现代码如下:
processed_items = [] for item in api_response: # 筛选当前条目的有效属性 valid_attributes = [attr for attr in item["attributes"] if "attributeId" in attr] # 生成新条目避免修改原始返回数据 new_item = item.copy() new_item["attributes"] = valid_attributes processed_items.append(new_item)
核心访问逻辑说明
- 嵌套数组内字典的键可以通过
外层字典["attributes"][索引]["attributeId"]的层级规则访问,判断键是否存在使用"attributeId" in 字典语法,可避免直接访问不存在的键抛出KeyError。 - 若需要读取
attributeId的具体值,在确认键存在后直接用attr["attributeId"]读取即可。
内容的提问来源于stack exchange,提问作者Suzdar Ibrahim
相关产品推荐
相关产品推荐

