ใน Python มี container ชื่อ Dictionary แมป key ไปยัง value เข้าถึงค่าได้ใน constant time แต่ถ้า key ไม่มีอยู่ จะเกิด KeyError
ปัญหา: KeyError
country_dict = {'India': 'IN', 'Australia': 'AU', 'Brazil': 'BR'}
print(country_dict['Australia']) # AU
print(country_dict['Canada']) # KeyError: 'Canada'
วิธีที่ 1: ใช้ get() (แนะนำมากที่สุด)
dict.get(key, default) - คืนค่า value ถ้ามี key, ไม่มีคืน default (default เป็น None ถ้าไม่ระบุ)
country_dict = {'India': 'IN', 'Australia': 'AU', 'Brazil': 'BR'}
print(country_dict.get('Australia', 'Not Found')) # AU
print(country_dict.get('Canada', 'Not Found')) # Not Found
ผลลัพธ์
AU
Not Found
วิธีที่ 2: ใช้ setdefault()
คล้าย get() แต่ เพิ่ม key ใหม่พร้อม default value ลงใน dictionary ถ้า key ไม่มี
country_dict = {'India': 'IN', 'Australia': 'AU', 'Brazil': 'BR'}
country_dict.setdefault('Canada', 'Not Present')
print(country_dict['Australia']) # AU
print(country_dict['Canada']) # Not Present
print(country_dict) # Canada ถูกเพิ่มเข้าไปแล้ว
ผลลัพธ์
AU
Not Present
{'India': 'IN', 'Australia': 'AU', 'Brazil': 'BR', 'Canada': 'Not Present'}
วิธีที่ 3: ใช้ defaultdict (จาก collections)
Container ที่ตั้งค่า default factory ไว้ ตอน key ไม่มี จะสร้างค่า default อัตโนมัติ
import collections as col
# default factory คืนสตริงนี้
country_dict = col.defaultdict(lambda: 'Key Not Present')
country_dict['India'] = 'IN'
country_dict['Australia'] = 'AU'
country_dict['Brazil'] = 'BR'
print(country_dict['Australia']) # AU
print(country_dict['Canada']) # Key Not Present (ไม่เกิด error)
print(country_dict['Japan']) # Key Not Present
ผลลัพธ์
AU
Key Not Present
Key Not Present
สรุปการเลือกใช้
| วิธี | เพิ่ม key ใหม่? | เหมาะสำหรับ |
|---|---|---|
get() | ไม่ | อ่านอย่างเดียว ไม่อยากเปลี่ยน dict |
setdefault() | ใช่ (ครั้งเดียว) | ต้องการให้ key มีค่า default คงที่ |
defaultdict | ใช่ (ทุกครั้ง) | ต้องการ default แบบ dynamic (เช่น list, int) |
ตัวอย่าง defaultdict กับ list (นิยมมาก)
from collections import defaultdict
# จับกลุ่มคำตามตัวอักษรแรก
words = ['apple', 'banana', 'apricot', 'cherry', 'blueberry']
grouped = defaultdict(list)
for word in words:
grouped[word[0]].append(word)
print(dict(grouped))
# {'a': ['apple', 'apricot'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}