如何从字典嵌套列表中查询attribute_code为city对应的value并解决报错
问题原因分析
- 首先你混淆了列表和字典的访问规则:
custom_attributes对应的值是*列表(数组)*类型,列表不能直接用字符串作为索引访问,必须先通过下标或者遍历的方式拿到列表里的每一个字典元素。 - 你的写法
list["custom_attributes"]["attribute_code"]试图直接用字符串索引访问列表,直接触发了TypeError类型错误。
正确实现方法
方法1:遍历法(最易理解)
# 假设你的原数据存储在变量 data 中 target_value = None for attr in data["custom_attributes"]: if attr["attribute_code"] == "city": target_value = attr["value"] break # 找到后直接退出循环,避免无效遍历 print(target_value)
方法2:生成器表达式(写法更简洁)
target_value = next(attr["value"] for attr in data["custom_attributes"] if attr["attribute_code"] == "city")
注意:如果不确定一定存在
attribute_code为city的元素,可以给next加默认值避免抛出StopIteration异常:target_value = next((attr["value"] for attr in data["custom_attributes"] if attr["attribute_code"] == "city"), None)
内容的提问来源于stack exchange,提问作者OdiumPura
相关产品推荐
相关产品推荐

