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

Python中如何从嵌套键内获取指定键的值?

获取嵌套结构中指定键的值

你的数据结构里,"fruit"对应的是一个列表,列表里的第一个元素就是包含"oranges"键的字典,你可以通过以下几种方式获取对应值:

直接访问

通过索引定位列表元素,再通过键名取值:

a = {"fruit":[{"oranges":['10']},{"apples":['11']}]}
oranges_value = a["fruit"][0]["oranges"]
print(oranges_value)  # 输出: ['10']

安全访问(避免报错)

如果担心"fruit"不存在、列表为空或"oranges"键不存在,用get()方法做容错处理,避免抛出异常:

# 即使对应键/索引不存在,也会返回默认的空列表,不会报错
oranges_value_safe = a.get("fruit", [{}])[0].get("oranges", [])
print(oranges_value_safe)

遍历查找(不确定键的位置时)

如果不确定"oranges"在列表的哪个元素里,可以遍历列表逐一查找:

for item in a.get("fruit", []):
    if "oranges" in item:
        print(item["oranges"])
        break

内容的提问来源于stack exchange,提问作者I desperatly need help

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 14:25:24