เมธอด update() ของ Dictionary ใช้สำหรับ อัปเดตหรือเพิ่ม Key-Value pairs หลายคู่พร้อมกัน
ไวยากรณ์
dictionary_name.update(other_dictionary_or_iterable)
- อาร์กิวเมนต์สามารถเป็น Dictionary อื่น หรือ Iterable ของ Key-Value Pairs (เช่น List of Tuples)
- Key ที่มีอยู่แล้ว → ค่าจะถูก ทับใหม่
- Key ใหม่ → จะถูก เพิ่มเข้าไป
ตัวอย่าง: อัปเดตสต็อกหนังสือ
book = {
'title': 'The Great Gatsby',
'published': '1925',
'author': 'F. Scott Fitzgerald',
'in_stock': False
}
new_stock = {'in_stock': True}
book.update(new_stock)
print(book)
# {'title': 'The Great Gatsby', 'published': '1925', 'author': 'F. Scott Fitzgerald', 'in_stock': True}
รูปแบบอื่นๆ ที่ใช้ได้
1. ใช้ Iterable ของ Tuples
book.update([('price', 29.99), ('pages', 180)])
# เพิ่ม price และ pages
2. ใช้ Keyword Arguments
book.update(genre='Fiction', rating=4.5) # เพิ่ม genre และ rating
สรุป
dict.update() เป็นวิธีมาตรฐานและมีประสิทธิภาพสำหรับ Merge Dictionary หรืออัปเดตหลายค่าพร้อมกัน เขียนโค้ดสั้น กระชับ และอ่านง่าย