CT2131
CT2131

Reputation: 21

Iterate through a list of dictionaries

Iterate through the list of dictionaries and print out each high school and their types

A dictionary of high schools and the type of school.

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)

Resulting in error: 'list' object has no attribute 'items'

Upvotes: 0

Views: 4243

Answers (1)

Mous
Mous

Reputation: 1047

TL;DR

You've made a typo on line 7, which should be

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

Full code

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)

Long version

lists don't have a .items() method, but dictionaries do. When the erroneous items() method (which doesn't exist) of high_school_types is called, Python throws an error, because this doesn't exist.

Instead, you need to index into high_school_types using your loop variable, index. This indexed value will be a dictionary and will have the .items() method.

References

Dictionary Objects documentation

Data Structures documentation

Upvotes: 3

Related Questions