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

Python使用for循环遍历嵌套字典,如何提取指定的teacher、students字段

代码调整方案

你的原有循环只遍历了一级机构下的所有属性字段,没有精准定位到目标层级的firstclass数据,因此无法得到预期输出。
调整后的可运行代码如下:

for org in data.values():
    first_class = org['class']['firstclass']
    print(f"'teacher':'{first_class['teacher']}','students':'{first_class['students']}'")

代码逻辑说明

  • 遍历data字典的所有值,直接拿到school/college/university对应的属性字典
  • 按照字典层级依次取值:先取class属性,再取class下的firstclass属性,即可得到包含teacher和students的目标字典
  • 按照要求的字符串格式拼接输出
    运行后输出结果和你预期完全一致:
'teacher':'b','students':'10'
'teacher':'d','students':'9'
'teacher':'f','students':'55'

如果你的实际数据可能存在class或firstclass键缺失的情况,可以加一层判断避免报错,示例如下:

for org in data.values():
    if 'class' in org and 'firstclass' in org['class']:
        first_class = org['class']['firstclass']
        print(f"'teacher':'{first_class['teacher']}','students':'{first_class['students']}'")

内容的提问来源于stack exchange,提问作者Krishna Prasad

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 12:36:02