เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

การตรวจสอบข้อมูลใน 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 อยู่ใน dictionary squirrels_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')
แก้ไขและรันโค้ด