遍历字典列表

时间:2021-07-14 05:21:52

标签: python

遍历字典列表并打印出每个高中及其类型

高中字典和学校类型。

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)):
    for key, value in high_school_types.items():
        print(key, value)

导致错误:'list' 对象没有属性 'items'

1 个答案:

答案 0 :(得分:1)

TL;DR

您在第 7 行打错了字,应该是

for key, value in high_school_types[index].items():

完整代码

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)):
    for key, value in high_school_types[index].items():
        print(key,value)

长版

lists 没有 .items() 方法,但字典有。当调用 items() 的错误 high_school_types 方法(不存在)时,Python 会抛出错误,因为它不存在。

相反,您需要使用循环变量 high_school_types 索引到 index。此索引值将是一个字典,并具有 .items() 方法。

参考资料

Dictionary Objects documentation

Data Structures documentation