走訪字典
在 Python 3 中,你需要使用 items() 方法來走訪字典:
world = { "afghanistan":30.55,
"albania":2.77,
"algeria":39.21 }
for key, value in world.items() :
print(key + " -- " + str(value))
還記得 europe 這個字典嗎?它以一些歐洲國家的名稱作為鍵,並以對應的首都作為值。現在請撰寫一個迴圈來逐一走訪它吧!
本練習屬於課程
Python 中級
練習說明
撰寫一個 for 迴圈,逐一走過 europe 的每個 key:value 配對。每次迭代時,都要印出 "the capital of x is y",其中 x 是鍵、y 是對應的值。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Definition of dictionary
europe = {'spain':'madrid', 'france':'paris', 'germany':'berlin',
'norway':'oslo', 'italy':'rome', 'poland':'warsaw', 'austria':'vienna' }
# Iterate over europe