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
相关产品推荐
相关产品推荐

