You need to enable JavaScript to run this app. Python遍历字典列表打印高中信息时出现list无items属性报错问题
优惠活动
大模型
产品
解决方案
定价
更多

Python遍历字典列表打印高中信息时出现list无items属性报错问题

报错原因分析
  • high_school_types是存储字典的列表类型,items()是Python中字典类型的专属方法,列表本身没有该方法,直接对列表调用items()就会触发该报错。
  • 原代码中虽然通过index遍历了列表的索引,但没有通过索引取出对应位置的字典元素,就直接对外层列表调用items(),逻辑也不符合需求。
正确实现代码

写法1:基于原有索引遍历逻辑修改

high_school_types = [{"High School": "Griffin", "Type":"District"},
                    {"High School": "Figueroa", "Type": "District"},
                    {"High School": "Wilson", "Type": "Charter"},
                    {"High School": "Wright", "Type": "Charter"}]

for index in range(len(high_school_types)):
    # 先通过索引取出当前位置的字典元素
    school_info = high_school_types[index]
    # 打印高中名称和对应类型
    print(f"高中名称:{school_info['High School']},学校类型:{school_info['Type']}")

写法2:更简洁的直接遍历列表元素写法(推荐)

high_school_types = [{"High School": "Griffin", "Type":"District"},
                    {"High School": "Figueroa", "Type": "District"},
                    {"High School": "Wilson", "Type": "Charter"},
                    {"High School": "Wright", "Type": "Charter"}]

for school_info in high_school_types:
    print(f"高中名称:{school_info['High School']},学校类型:{school_info['Type']}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 05:45:01