Dictionaries (records)
เก็บข้อมูลด้วยชื่อ
- Dictionary เก็บค่าภายใต้ชื่อที่เรียกว่า keys
- เขียนคู่ภายในวงเล็บปีกกา:
{"name": "Sam", "age": 15} - แต่ละ key มีเอกลักษณ์และชี้ไปยังค่าเดียว
ดึงและตั้งค่า
- อ่านค่าด้วย key ของมัน:
person["name"] - เพิ่มหรือแก้ไขค่าแบบเดียวกัน:
person["age"] = 16 - List ใช้ตัวเลข index; Dictionary ใช้ key
ages = {"Sam": 12, "Mia": 15}
print(ages["Sam"])
ages["Leo"] = 9
print(ages)
Dictionary เป็น record
- Record กลุ่มข้อมูลที่สัมพันธ์กันเกี่ยวกับสิ่งใดสิ่งหนึ่ง
- Dictionary เป็นวิธีที่ดีในการจัดเก็บ record
- แต่ละ key เป็น field, เช่น
nameหรือgrade
pupil = {"name": "Ada", "grade": "A"}
print(pupil["name"])
print(pupil["grade"])
ตรวจสอบและวนลูป
"name" in personเป็นTrueหากรายการนั้นมีอยู่for key in person:เยือนแต่ละ key ตามลำดับperson.get("x", 0)ส่งค่า default หาก key หายไป
menu = {"tea": 2, "cake": 5}
for item in menu:
print(item, menu[item])
print("tea" in menu)
In Cambridge pseudocode
- Dictionaryจำลอง exam's
TYPErecord; Each key is a field reached with a dot
TYPE Student
DECLARE Name : STRING
DECLARE Age : INTEGER
ENDTYPE
DECLARE Pupil : Student
Pupil.Name ← "Sam"
Pupil.Age ← 15
ข้อผิดพลาดที่พบบ่อย
- อ่านค่าด้วย key ของมัน:
d["name"]; A missing key raises a KeyError - คีย์มีความไม่ซ้ำกัน — การกำหนดคีย์เดิมซ้ำจะแทนที่ค่าเดิม
- ใช้
d.get(key)เมื่อ key อาจหายไป
ลองดูเลย
- สร้างหรืออัปเดต dictionary ในแต่ละงาน
- กด Check answer เพื่อทดสอบโค้ดของคุณ
Look up by key
A dictionary jumps straight to the value for a key — no scanning.
ความยาก 3/5 · 200 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Create a dictionary book with two keys: title set to "Python" และ pages set to 200.
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 3/5 · 200 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
The dictionary student already has name และ score. Change score ไป 85, and add a new key passed set to True.
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 3/5 · 200 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Loop over the dictionary prices and add up its values. Store the total in total (the answer is 10).
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 3/5 · 200 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Write count_words(text) that ผลตอบแทน a dictionary: each word of text (split on spaces) mapped to how many times it appears. count_words("the cat and the hat") gives {"the": 2, "cat": 1, "and": 1, "hat": 1}.
คลิก Run เพื่อดูผลลัพธ์ที่นี่