การตรวจสอบข้อมูลใน Dictionary
สามารถตรวจสอบว่า key มีอยู่ใน dictionary หรือไม่ โดยใช้ expression in
ตัวอย่างเช่น หากต้องการตรวจสอบว่า 'cookies' เป็น key ใน dictionary ชื่อ recipes ให้ใช้ if 'cookies' in recipes: วิธีนี้ช่วยให้จัดการกับข้อมูลที่อาจมีหรือไม่มีใน dictionary ได้อย่างปลอดภัย
เราได้โหลด dictionary ชื่อ squirrels_by_park ให้แล้ว โดยใช้ชื่อสวนสาธารณะเป็น key และมีค่าเป็น list ของ dictionary ข้อมูลกระรอก
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
ประเภทข้อมูลใน Python
คำแนะนำการฝึกหัด
- ตรวจสอบว่า
Tompkins Square Parkอยู่ใน dictionarysquirrels_by_parkหรือไม่ และพิมพ์'Found Tompkins Square Park'หากพบ - ตรวจสอบว่า
Central Parkอยู่ในsquirrels_by_parkหรือไม่ จากนั้นพิมพ์'Found Central Park'หากพบ หรือพิมพ์'Central Park missing'หากไม่พบ
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Check to see if Tompkins Square Park is in squirrels_by_park
if "____" ____ ____:
# Print 'Found Tompkins Square Park'
print('Found Tompkins Square Park')
# Check to see if Central Park is in squirrels_by_park
if "____" ____ ____:
# Print 'Found Central Park' if found
print('Found Central Park')
else:
# Print 'Central Park missing' if not found
print('Central Park missing')