
เขียนโปรแกรมภาษา Python ตอนที่ 120 การเปลี่ยนแปลงข้อมูลใน Dictionary
เราสามารถเปลี่ยนแปลงค่าข้อมูลใน Dictionary โดยการระบุ key ดังนี้
phone = { "brand": "Apple", "model": "iPhone 14", "year": 2022, "colors": ["Red", "Blue", "White", "Black", "Purple"], "price": 40000 } print("Price before change : " + str(phone["price"])) phone["price"] = 39700 print("Price after change : " + str(phone["price"]))
- บรรทัดที่ 9 เข้าถึงข้อมูลใน Dictionary โดยการระบุ key แล้วกำหนดค่าใหม่ลงไป
ผลลัพธ์
Price before change : 40000
Price after change : 39700
เมธอด update()
นอกจากการระบุ key และกำหนดค่าใหม่ ดังกล่าวข้างต้นแล้ว เราสามารถเปลี่ยนแปลงค่าใน Dictionary ด้วยเมธอด update()
อีกด้วย โดยมีรูปแบบการใช้งานดังนี้
dict.update({key:value})
- การใช้เมธอด
update()
ต้องมีการผ่านค่า Argument เข้าไป (เป็น Dictionary หรือประเภทข้อมูลที่มีการอ้างอิงแบบ key:value)
ตัวอย่าง
phone = { "brand": "Apple", "model": "iPhone 14", "year": 2022, "colors": ["Red", "Blue", "White", "Black", "Purple"], "price": 40000 } print("Price before change : " + str(phone["price"])) phone.update({"price":39700}) print("Price after change : " + str(phone["price"]))
- บรรทัดที่ 9 ใช้เมธอด
update()
แก้ไขค่าใน Dictionary โดยส่ง Argument เข้าไปเป็น Dictionary ที่มี key ตรงกับ key ที่มีอยู่ใน Dictionary ต้นทาง และกำหนดค่าใหม่เข้าไป
ผลลัพธ์
Price before change : 40000
Price after change : 39700