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

Mapping Types ใน Python: Dictionary


ออบเจ็กต์ mapping ใช้จับคู่ค่าแฮช (hash table) กับออบเจ็กต์ตามต้องการ ใน Python มี mapping type คือ dictionary ซึ่งเป็น mutable (แก้ไขได้)

Key ของ dictionary สามารถเป็นอะไรก็ได้ Value สามารถเป็น list, integer หรือออบเจ็กต์ mutable อื่นๆ

เมธอดและออปอเรชันสำคัญ

เมธอด/ออปอเรชันคำอธิบาย
len(d)จำนวนอิลิเมนต์ใน dictionary
d[k]คืนค่า item ที่มี key 'k' อาจเกิด KeyError หากไม่มี key
iter(d)คืน iterator ของ keys (เหมือน iter(d.keys()))
get(key[, default])คืนค่าจาก key พร้อมค่า default ถ้าไม่มี key
items()คืนคู่ (key, value)
keys()คืนรายการ keys ทั้งหมด
values()คืนรายการ values ทั้งหมด
update(elem)อัปเดตอิลิเมนต์ใน dictionary

ตัวอย่างโค้ด

myDict = {'ten': 10, 'twenty': 20, 'thirty': 30, 'forty': 40}
print(myDict)
print(list(myDict.keys()))
print(list(myDict.values()))
print(list(myDict.items()))
myDict.update({'fifty': 50})
print(myDict)

ผลลัพธ์

{'ten': 10, 'twenty': 20, 'thirty': 30, 'forty': 40}
['ten', 'twenty', 'thirty', 'forty']
[10, 20, 30, 40]
[('ten', 10), ('twenty', 20), ('thirty', 30), ('forty', 40)]
{'ten': 10, 'twenty': 20, 'thirty': 30, 'forty': 40, 'fifty': 50}