Reputation: 21
Iterate through the list of dictionaries and print out each high school and their types
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
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
Upvotes: 3