Python ตอนที่ 121 การเพิ่มข้อมูลใน Dictionary

การเพิ่มข้อมูลใหม่เข้าไปใน Dictionary สามารถทำได้ง่าย ๆ โดยการระบุ key ใหม่ และกำหนด value ใหม่ ดังนี้

phone = {
    "brand": "Apple",
    "model": "iPhone 14",
    "year": 2022
}
print("Before adding new item :")
print(phone)

phone["price"] = 37900

print("After adding new item :")
print(phone)
  • บรรทัดที่ 9 เพิ่มข้อมูลใหม่เข้าไปใน Dictionary โดยการระบุ key และ value ใหม่เข้าไป

ผลลัพธ์

Before adding new item :
{‘brand’: ‘Apple’, ‘model’: ‘iPhone 14’, ‘year’: 2022}
After adding new item :
{‘brand’: ‘Apple’, ‘model’: ‘iPhone 14’, ‘year’: 2022, ‘price’: 37900}

หมายเหตุ : ถ้าคีย์ที่ระบุ ซ้ำกับคีย์เดิมที่มีอยู่แล้ว จะเป็นการเปลี่ยนแปลงค่าของ key เดิม

เพิ่มข้อมูลใหม่ด้วยเมธอด update()

เมธอด update() ใช้สำหรับเปลี่ยนแปลงข้อมูลใน Dictionary โดยมีรูปแบบการใช้งานดังนี้

dict.update({key:value})
  • เมธอด update() รับ argument 1 ตัว เป็น Dictionary หรือข้อมูลประเภทอื่นที่มีการเก็บข้อมูลแบบ key:value

ดังที่กล่าวข้างต้นว่า เมธอด update() ใช้นำหรับการเปลี่ยนแปลงข้อมูลใน Dictionary โดยต้องมีการระบุ Argument เป็น Dictionary หรือข้อมูลประเภทอื่นที่มีการอ้างอิงแบบ key:value โดยเมธอดนี้จะทำการแก้ไขค่าของสมาชิกที่มี key ตรงกับที่ระบุ

แต่ถ้า key ที่ระบุ ไม่มีอยู่ใน Dictionary ต้นทาง จะเป็นการเพิ่มข้อมูลเข้าไปใหม่ ดังนั้น เราจึงสามารถใช้เมธอด update() นี้ในการเพิ่มข้อมูลใน Dictionary ได้นั่นเอง

ตัวอย่าง

phone = {
    "brand": "Apple",
    "model": "iPhone 14",
    "year": 2022
}
print("Before adding new item :")
print(phone)

phone.update({"price": 37900})

print("After adding new item :")
print(phone)
  • บรรทัดที่ 9 ใช้เมธอด update() ทำการแก้ไขข้อมูลใน Dictionary โดยระบุ Argument เป็นข้อมูลแบบ Dictionary ซึ่งมี key = price และ value = 37900 แต่เนื่องจากใน Dictionary ต้นทาง ไม่มีคีย์ price อยู่ จึงเป็นการเพิ่มข้อมูลเข้าไปใหม่

ผลลัพธ์

Before adding new item :
{‘brand’: ‘Apple’, ‘model’: ‘iPhone 14’, ‘year’: 2022}
After adding new item :
{‘brand’: ‘Apple’, ‘model’: ‘iPhone 14’, ‘year’: 2022, ‘price’: 37900}