Dictionaries (records) · Từ điển (bản ghi)
Store data by name
- A dictionary stores values under names called keys.
- Write pairs inside braces:
{"name": "Sam", "age": 15}. - Each key is unique and points to one value.
Lưu trữ dữ liệu theo tên
- Một từ điển (dictionary) lưu trữ các giá trị dưới các tên gọi là khóa (keys).
- Viết các cặp bên trong dấu ngoặc nhọn:
{"name": "Sam", "age": 15}. - Mỗi khóa là duy nhất và trỏ đến một giá trị.
Get and set values
- Read a value with its key:
person["name"]. - Add or change a value the same way:
person["age"] = 16. - A list uses a number index; a dictionary uses a key.
Lấy và đặt giá trị
- Đọc giá trị thông qua khóa của nó:
person["name"]. - Thêm hoặc thay đổi giá trị theo cách tương tự:
person["age"] = 16. - Danh sách sử dụng chỉ số là số; từ điển sử dụng khóa.
ages = {"Sam": 12, "Mia": 15}
print(ages["Sam"])
ages["Leo"] = 9
print(ages)
A dictionary as a record
- A record groups related facts about one thing.
- A dictionary is a neat way to hold a record.
- Each key is a field, like
nameorgrade.
Từ điển như một bản ghi
- Một bản ghi (record) nhóm các thông tin liên quan về một đối tượng.
- Từ điển là cách gọn gàng để chứa một bản ghi.
- Mỗi khóa là một trường (field), giống như
namehoặcgrade.
pupil = {"name": "Ada", "grade": "A"}
print(pupil["name"])
print(pupil["grade"])
Check and loop
"name" in personisTrueif that key exists.for key in person:visits each key in turn.person.get("x", 0)returns a default if the key is missing.
Kiểm tra và lặp
"name" in personsẽ làTruenếu khóa đó tồn tại.for key in person:duyệt qua từng khóa một.person.get("x", 0)trả về giá trị mặc định nếu khóa bị thiếu.
menu = {"tea": 2, "cake": 5}
for item in menu:
print(item, menu[item])
print("tea" in menu)
In Cambridge pseudocode
- A dictionary models the exam's
TYPErecord; each key is a field reached with a dot.
Trong pseudocode Cambridge
- Từ điển mô phỏng bản ghi exam
TYPE; mỗi khóa là một trường truy cập bằng dấu chấm.
TYPE Student
DECLARE Name : STRING
DECLARE Age : INTEGER
ENDTYPE
DECLARE Pupil : Student
Pupil.Name ← "Sam"
Pupil.Age ← 15
Common mistakes
- Read a value by its key:
d["name"]; a missing key raises a KeyError. - Keys are unique — assigning the same key again overwrites the value.
- Use
d.get(key)when the key might be missing.
Lỗi thường gặp
- Đọc giá trị theo khóa:
d["name"]; việc truy cập khóa bị thiếu sẽ gây lỗi KeyError. - Khóa là duy nhất — gán lại cho cùng một khóa sẽ ghi đè lên giá trị cũ.
- Dùng
d.get(key)khi khóa có thể bị thiếu.
Now you try
- Build or update a dictionary in each task.
- Press Check answer to test your code.
Bây giờ bạn thử
- Xây dựng hoặc cập nhật từ điển trong mỗi bài tập.
- Nhấn Check answer (Kiểm tra câu trả lời) để thử mã của bạn.
Look up by key · Tra cứu theo khóa
A dictionary jumps straight to the value for a key — no scanning. · Từ điển nhảy thẳng đến giá trị cho một khóa — không cần quét.
Create a dictionary book with two keys: title set to "Python" and pages set to 200. · Tạo từ điển book với hai khóa: title đặt thành "Python" và pages đặt thành 200.
Click Run to see the output here. · Nhấn Chạy để xem kết quả ở đây.
The dictionary student already has name and score. Change score to 85, and add a new key passed set to True. · Từ điển student đã có sẵn name và score. Đổi score thành 85, và thêm một khóa mới passed đặt thành True.
Click Run to see the output here. · Nhấn Chạy để xem kết quả ở đây.
Loop over the dictionary prices and add up its values. Store the total in total (the answer is 10). · Lặp qua từ điển prices và cộng tổng các giá trị của nó. Lưu tổng vào total (đáp án là 10).
Click Run to see the output here. · Nhấn Chạy để xem kết quả ở đây.
Write count_words(text) that returns 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}. · Viết count_words(text) trả về một từ điển: mỗi từ của text (tách dựa trên khoảng trắng) được ánh xạ với số lần xuất hiện của nó. count_words("the cat and the hat") đưa ra {"the": 2, "cat": 1, "and": 1, "hat": 1}.
Click Run to see the output here. · Nhấn Chạy để xem kết quả ở đây.