[英]Iterate through a list of dictionaries
遍歷字典列表並打印出每個高中及其類型
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'
TL; 博士
你在第 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()
方法,但字典有。 當調用high_school_types
的錯誤items()
方法(不存在)時,Python 會拋出錯誤,因為它不存在。
相反,您需要使用循環變量 index 對high_school_types
進行index
。 這個索引值將是一個字典,並將具有.items()
方法。
參考
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.