Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธี Update ค่าของ Key ใน Dictionary ใน Python

Python Dictionary Object เป็น Unordered Collection ของคู่ Key:Value ใน Dictionary Object d ค่าที่เชื่อมโยงกับ Key ใดๆ สามารถเข้าถึงได้ด้วย d[k]

>> d = {'one': 1, 'two': 2, 'three': 3, 'four': 4}
>>> d['two']
2

การกำหนด d[k] = v จะ Update Dictionary Object หากใช้ Existing Key ใน Expression ค่าที่เชื่อมโยงจะถูก Update หาก Key ยังไม่ได้ใช้ คู่ Key-Value ใหม่จะถูกเพิ่มใน Dictionary Object

>> d = {'one': 1, 'two': 2, 'three': 3, 'four': 4}
>>> d['two'] = 22
>>> d
{'one': 1, 'two': 22, 'three': 3, 'four': 4}
>>> d['five'] = 5
>>> d
{'one': 1, 'two': 22, 'three': 3, 'four': 4, 'five': 5}