วนลูปผ่าน dictionary
ใน Python 3 ต้องใช้เมธอด items() เพื่อวนลูปผ่าน dictionary:
world = { "afghanistan":30.55,
"albania":2.77,
"algeria":39.21 }
for key, value in world.items() :
print(key + " -- " + str(value))
จำ dictionary ชื่อ europe ที่เก็บชื่อประเทศในยุโรปเป็น key และเมืองหลวงเป็น value ได้ไหม? ลองเขียนลูปเพื่อวนซ้ำผ่านข้อมูลใน dictionary นี้ดูกัน!
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Python ระดับกลาง
คำแนะนำการฝึกหัด
เขียนลูป for เพื่อวนผ่านทุก key:value pair ใน europe ในแต่ละรอบให้พิมพ์ข้อความในรูปแบบ "the capital of x is y" โดยที่ x คือ key และ y คือ value ของคู่นั้น
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Definition of dictionary
europe = {'spain':'madrid', 'france':'paris', 'germany':'berlin',
'norway':'oslo', 'italy':'rome', 'poland':'warsaw', 'austria':'vienna' }
# Iterate over europe