การใช้งาน dictionary

ประเภทข้อมูลใน Python

Jason Myers

Instructor

การสร้างและวนลูปใน dictionary

  • เก็บข้อมูลในรูปแบบคู่ key/value
  • ซ้อนกันได้ (ใช้ dictionary เป็นค่าของ key ภายใน dictionary)
  • วนซ้ำได้
  • สร้างด้วย dict() หรือ {}
art_galleries = {}

for name, zip_code in galleries:
    art_galleries[name] = zip_code
ประเภทข้อมูลใน Python

การพิมพ์ข้อมูลในลูป

for name in sorted(art_galleries)[-5:]:
    print(name)
Zwirner David Gallery
Zwirner & Wirth
Zito Studio Gallery
Zetterquist Galleries
Zarre Andre Gallery
ประเภทข้อมูลใน Python

การค้นหาด้วย key อย่างปลอดภัย

art_galleries['Louvre']
|--------------------------------------------------------------------
KeyError                            Traceback (most recent call last)
<ipython-input-1-4f51c265f287> in <module>()
--> 1 art_galleries['Louvre']

KeyError: 'Louvre'
  • การดึงค่าจาก dictionary ใช้ key เป็น index
  • หากระบุ key ที่ไม่มีอยู่ โปรแกรมจะหยุดทำงานพร้อม KeyError
ประเภทข้อมูลใน Python

การค้นหาด้วย key อย่างปลอดภัย (ต่อ)

  • เมธอด .get() ช่วยให้เข้าถึง key ได้โดยไม่เกิดข้อผิดพลาด
  • หาก key ไม่อยู่ใน dictionary .get() จะคืนค่า None หรือระบุค่าเริ่มต้นเองได้
art_galleries.get('Louvre', 'Not Found')
'Not Found'
art_galleries.get('Zarre Andre Gallery')
'10011'
ประเภทข้อมูลใน Python

มาฝึกกันเถอะ!

ประเภทข้อมูลใน Python

Preparing Video For Download...