Phương thức dict.get(key[, default]) truy xuất giá trị an toàn: trả về giá trị nếu key tồn tại, ngược lại trả về default (mặc định None) thay vì raise KeyError.
Cú pháp
dict.get(key, default=None)
Ví dụ so sánh
customer = {'Address': 'Hawaii', 'Distance': 358}
# Truy xuất trực tiếp (raise KeyError nếu key không tồn tại)
print(customer["Address"]) # Hawaii
# Dùng get() - an toàn
print('Address:', customer.get('Address')) # Hawaii
print('Distance:', customer.get('Distance')) # 358
# Key không tồn tại
print('Amount:', customer.get('Amount')) # None (không lỗi)
# Key không tồn tại + default value
print('Amount:', customer.get('Amount', 2050.0)) # 2050.0
Kết quả
Hawaii Address: Hawaii Distance: 358 Amount: None Amount: 2050.0
Khi nào dùng get() thay vì dict[key]?
- Key có thể không tồn tại (optional field)
- Cần giá trị mặc định (default value)
- Tránh try/except KeyError cho code gọn hơn
Ví dụ thực tế: Cấu hình với default
config = {'debug': True, 'port': 8080}
debug = config.get('debug', False)
port = config.get('port', 5000)
host = config.get('host', 'localhost')
timeout = config.get('timeout', 30)
print(f"Server: {host}:{port}, debug={debug}, timeout={timeout}s")
Kết luận
get() là cách Pythonic để truy xuất dictionary an toàn, hỗ trợ default value, tránh KeyError.