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

如何从字典嵌套列表中查询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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 20:15:03