ในบทช่วยสอนนี้ เราจะเรียนรู้วิธีใช้ Dictionary Comprehension ใน Python หากคุณคุ้นเคยกับ List Comprehension แล้ว จะเรียนรู้ได้รวดเร็วมาก
รูปแบบพื้นฐานของ Dictionary Comprehension
{key: value for item in iterable}
เราต้องระบุ key และ value จากแต่ละ item ใน iterable มีหลายวิธีในการทำ เรามาดูตัวอย่างที่พบบ่อยที่สุดกัน
1. สร้าง Dictionary จากช่วงตัวเลข (Key = ตัวเลข, Value = กำลังสอง)
ผลลัพธ์ที่ต้องการ: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
# สร้าง dictionary ด้วย comprehension
squares = {i: i ** 2 for i in range(10)}
# แสดงผล
print(squares)
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
2. สร้าง Dictionary จากสอง List ด้วย zip()
ใช้ zip() เพื่อจับคู่ค่าจากสองลิสต์พร้อมกัน
keys = ['a', 'b', 'c', 'd', 'e']
values = [1, 2, 3, 4, 5]
# สร้าง dict จากสองลิสต์
dictionary = {key: value for (key, value) in zip(keys, values)}
print(dictionary)
# {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
3. สร้าง Dictionary จาก List เดียว โดยใช้ Index เป็น Key (enumerate)
values = ['a', 'b', 'c', 'd', 'e']
# ใช้ enumerate เพื่อดึง index และ value
dictionary = {key: value for (key, value) in enumerate(values)}
print(dictionary)
# {0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e'}
ประโยชน์ของ Dictionary Comprehension
- โค้ดกระชับ อ่านง่าย เขียนเร็ว
- ประสิทธิภาพดีกว่าการวนลูปปกติในหลายกรณี
- เหมาะสำหรับการแปลงข้อมูล (data transformation)
สรุป
Dictionary Comprehension เป็นเครื่องมือทรงพลังสำหรับสร้าง Dictionary อย่างมีประสิทธิภาพ ลองนำไปใช้ในโครงการจริงเพื่อเชี่ยวชาญทักษะนี้ได้ครับ
หากมีข้อสงสัย สามารถถามได้ในส่วนความคิดเห็นครับ