21. Kiểu dữ liệu Dictionary
Ở các bài học trước, bạn đã biết về List (Danh sách) và Tuple (Bộ), với 2 kiểu dữ liệu này, chúng ta sử dụng chỉ số (index) như 0, 1, 2....để truy cập tới các phần tử.
Nhưng hãy tưởng tượng, bạn có một chiếc tủ, gồm 40 ngăn, dùng để chứa đồ của 40 bạn trong lớp. Thay vì đánh số từ 0 đến 39, sẽ dễ dàng hơn nhiều nếu bạn dán tên mỗi bạn lên từng ngăn kéo. Khi cần tìm đồ của bạn "An", bạn chỉ việc nhìn vào ngăn có tên "An" là thấy ngay.
Trong Python, đó chính là cách Dictionary hoạt động. Nó không dùng số để đánh dấu mỗi phần tử, mà dùng một cái "Tên" (gọi là Key - Khóa) để trỏ tới một "Giá trị" (gọi là Value).
21.1 Dictionary là gì?
Dictionary là một tập hợp các dữ liệu không có thứ tự, có thể thay đổi và không được phép có các Khóa (Key) trùng nhau.
Dictionary được đặt trong cặp dấu ngoặc nhọn { }, với cấu trúc Khóa : Giá trị.
Ví dụ:
# Tạo một từ điển về chiếc điện thoại
dien_thoai = {
"hang": "Apple",
"mau_sac": "Titan",
"nam_ra_mat": 2023
}
print(dien_thoai)
21.2 Truy cập các phần tử
Để lấy giá trị của một món đồ, bạn dùng tên của Khóa đặt trong dấu ngoặc vuông [ ].
Ví dụ:
[Python]
# Lấy tên hãng sản xuất
hang_sx = dien_thoai["hang"]
print(f"Dien thoai nay cua hang: {hang_sx}") # Kết quả: Apple
Lưu ý: Nếu bạn gọi một Khóa không tồn tại, Python sẽ báo lỗi.
21.3 Thay đổi giá trị
Bạn có thể thay đổi giá trị của một Khóa đã có bằng cách gán giá trị mới cho nó.
Ví dụ:
[Python]
dien_thoai["nam_ra_mat"] = 2026
print(dien_thoai) # Năm ra mắt đã được cập nhật thành 2026
21.4 Thêm phần tử
Việc thêm một phần tử mới rất đơn giản: bạn chỉ cần tạo ra một Khóa mới và gán giá trị cho nó.
Ví dụ:
[Python]
dien_thoai["he_dieu_hanh"] = "iOS"
print(dien_thoai)
21.5 Xóa phần tử
Có nhiều cách để "dọn dẹp" từ điển của bạn:
- pop("tên_khóa"): Xóa phần tử có khóa chỉ định
- del: Xóa phần tử hoặc xóa cả cuốn từ điển
- clear(): Xóa sạch mọi thứ bên trong, chỉ để lại cái khung { } trống rỗng
Ví dụ:
[Python]
dien_thoai.pop("mau_sac") # Xóa màu sắc
print(dien_thoai)
21.6 Vòng lặp Dictionary
Bạn có thể dùng vòng lặp for để duyệt qua từ điển. Mặc định, vòng lặp sẽ trả về các Khóa.
Ví dụ:
[Python]
# In tất cả các Khóa trong từ điển
for x in dien_thoai:
print(x)
# In tất cả các Giá trị bằng phương thức .values()
for y in dien_thoai.values():
print(y)
# In cả Khóa và Giá trị bằng phương thức .items()
for x, y in dien_thoai.items():
print(f"{x} co gia tri la {y}")
21.7 Sao chép Dictionary
Bạn không thể sao chép bằng cách viết dict2 = dict1, vì nếu bạn sửa dict1 thì dict2 cũng bị sửa theo. Để tạo một bản sao độc lập, hãy dùng phương thức copy().
Ví dụ:
[Python]
ban_sao = dien_thoai.copy()
21.8 Dictionary lồng nhau
Một từ điển có thể chứa nhiều từ điển khác bên trong. Giống như một danh sách lớp chứa nhiều hồ sơ học sinh, mỗi hồ sơ lại là một từ điển nhỏ.
Ví dụ:
[Python]
gia_dinh = {
"con_trai" : {"ten": "An", "tuoi": 15},
"con_gai" : {"ten": "Binh", "tuoi": 10}
}
21.9 Các phương thức quan trọng
- keys(): Trả về danh sách tất cả các Khóa
- values(): Trả về danh sách tất cả các Giá trị
- items(): Trả về danh sách các cặp (Khóa, Giá trị)
- get("tên_khóa"): Lấy giá trị của khóa (an toàn hơn vì không bị lỗi nếu khóa không tồn tại)
21.10 Bài tập và câu hỏi
Bài 21a: Lưu cấu hình máy tính
Tạo một Dictionary tên may_tinh chứa các thông tin: chu_so_huu (tên bạn), phien_ban (1.0), mau_sac (tùy chọn). Hãy in ra câu: "Máy tính của [tên] phiên bản [phien_ban] đã sẵn sàng!".
Bài 21b: Nhật ký phép tính cuối cùng
Viết chương trình cho người dùng nhập 2 số và 1 phép tính (+, -, *, /). Sau khi tính xong, hãy lưu kết quả vào một Dictionary tên ket_qua gồm các khóa: so_a, so_b, phep_tinh, dap_an. In Dictionary đó ra màn hình.
Bài 21c: Danh sách các phép tính mẫu
Tạo một Dictionary chứa các hằng số toán học: pi : 3.14, e : 2.71. Viết chương trình cho phép người dùng nhập tên hằng số (ví dụ nhập "pi") và máy tính sẽ xuất ra giá trị tương ứng. Nếu không tìm thấy, hãy thông báo "Hằng số này chưa được cập nhật".
Bài 21d: Quản lý điểm số lớp học 8A
Yêu cầu:
Bạn được giao quản lý điểm thi học kỳ của một nhóm học sinh. Hãy tạo một Dictionary có tên lop_8A để lưu trữ thông tin. Mỗi phần tử trong lop_8A sẽ có Khóa là tên học sinh, và Giá trị là một Dictionary con chứa điểm các môn: Toan, Van, Anh.
Dữ liệu mẫu:
- An: Toán: 8.5, Văn: 7.0, Anh: 9.0
- Bình: Toán: 4.0, Văn: 5.5, Anh: 5.0
- Chi: Toán: 9.5, Văn: 8.5, Anh: 9.0
Nhiệm vụ của bạn:
Viết chương trình duyệt qua danh sách học sinh trong lop_8A
Với mỗi học sinh, hãy tính Điểm trung bình (ĐTB) của 3 môn
Dựa vào ĐTB để xếp hạng:
Giỏi: ĐTB > 8.0
Khá: 6.5 < ĐTB < 8.0
Trung bình: 5.0 < ĐTB < 6.5
Yếu: ĐTB < 5.0
In ra màn hình kết quả theo định dạng:
Học sinh [Tên]: ĐTB = [Giá trị], Xếp loại: [Loại]Tìm và in ra tên của học sinh có ĐTB cao nhất lớp
Câu hỏi ôn tập
Câu 21.1 Cấu trúc nào sau đây dùng để khai báo một Dictionary đúng cú pháp trong Python?
A. info = ["ten", "An", "tuoi", 15]
B. info = ("ten": "An", "tuoi": 15)
C. info = {"ten": "An", "tuoi": 15}
D. info = {"ten"; "An"; "tuoi"; 15}
Câu 21.2 Để xóa tất cả các phần tử trong một Dictionary và chỉ để lại một khung trống { }, bạn sử dụng phương thức nào?
A. pop()
B. clear()
C. del
D. remove()
Câu 21.3 Cho đoạn mã sau:
[Python]
kho = {"tao": 10, "cam": 5}
kho["nho"] = 20
kho["tao"] = 15
Sau khi thực thi, Dictionary kho sẽ có nội dung như thế nào?
A. {"tao": 10, "cam": 5, "nho": 20}
B. {"tao": 15, "cam": 5, "nho": 20}
C. {"tao": 10, "cam": 5, "tao": 15, "nho": 20}
D. Python báo lỗi vì khóa "tao" đã tồn tại
-----
21. Dictionary Data Type
In previous lessons, you learned about Lists and Tuples. With these two data types, we use an index (0, 1, 2...) to access elements.
But imagine you have a cabinet with 40 drawers for 40 students in a class. Instead of numbering them from 0 to 39, it would be much easier to label each drawer with a student's name. When you need to find "An's" belongings, you simply look for the drawer labeled "An."
In Python, this is exactly how a Dictionary works. It doesn't use numbers to index elements; instead, it uses a "Key" to point to a "Value."
21.1 What is a Dictionary?
A Dictionary is a collection of data that is unordered, changeable (mutable), and does not allow duplicate Keys.
Dictionaries are written with curly brackets { }, using the structure Key : Value.
Example:
Python
# Create a dictionary about a phone
phone = {
"brand": "Apple",
"color": "Titanium",
"release_year": 2023
}
print(phone)
21.2 Accessing Elements
To get the value of an item, use the Key name inside square brackets [ ].
Example:
Python
# Get the manufacturer name
brand_name = phone["brand"]
print(f"This phone is made by: {brand_name}") # Output: Apple
Note: If you call a Key that does not exist, Python will raise a KeyError.
21.3 Changing Values
You can change the value of an existing Key by assigning a new value to it.
Example:
Python
phone["release_year"] = 2026
print(phone) # Release year updated to 2026
21.4 Adding Elements
Adding a new element is simple: just create a new Key and assign a value to it.
Example:
Python
phone["os"] = "iOS"
print(phone)
21.5 Removing Elements
There are several ways to "clean up" your dictionary:
- pop("key_name"): Removes the element with the specified key
- del: Removes a specific element or deletes the entire dictionary
- clear(): Empties the dictionary, leaving an empty { }
Example:
Python
phone.pop("color") # Removes the color entry
print(phone)
21.6 Looping Through a Dictionary
You can use a for loop to iterate through a dictionary. By default, the loop returns the Keys.
Example:
Python
# Print all Keys
for x in phone:
print(x)
# Print all Values using the .values() method
for y in phone.values():
print(y)
# Print both Keys and Values using the .items() method
for x, y in phone.items():
print(f"{x} has the value {y}")
21.7 Copying a Dictionary
You cannot copy a dictionary simply by writing dict2 = dict1, because changes made to dict1 will also apply to dict2. To create an independent copy, use the copy() method.
Example:
Python
copy_phone = phone.copy()
21.8 Nested Dictionaries
A dictionary can contain other dictionaries inside it. It's like a class list containing multiple student profiles, where each profile is a small dictionary.
Example:
Python
family = {
"son" : {"name": "An", "age": 15},
"daughter" : {"name": "Binh", "age": 10}
}
21.9 Important Methods
- keys(): Returns a list of all Keys
- values(): Returns a list of all Values
- items(): Returns a list of (Key, Value) tuples
- get("key_name"): Retrieves the value of a key (safer because it doesn't crash if the key is missing).
21.10 Exercises
Task 21a: Computer Configuration
Create a Dictionary named computer containing: owner (your name), version (1.0), and color (your choice). Print the sentence: "The computer of [owner] version [version] is ready!".
Task 21b: Last Calculation Log
Write a program where the user enters 2 numbers and 1 operator (+, -, *, /). Save the result in a Dictionary named result with keys: num_a, num_b, operator, and answer. Print the Dictionary.
Task 21c: Constant Lookup
Create a Dictionary containing mathematical constants: pi : 3.14, e : 2.71. Write a program that allows the user to enter a constant name (e.g., "pi") and output the corresponding value. If not found, display "Constant not updated."
Task 21d: Class 8A Grade Management
Requirement: Manage the semester grades of a group of students. Create a Dictionary named class_8A. Each Key is a student's name, and the Value is a nested dictionary containing grades for: Math, Literature, English.
Sample Data:
- An: Math: 8.5, Literature: 7.0, English: 9.0
- Binh: Math: 4.0, Literature: 5.5, English: 5.0
- Chi: Math: 9.5, Literature: 8.5, English: 9.0
Your mission:
Loop through the student list in class_8A.
For each student, calculate the Average Grade (GPA).
Rank them based on GPA:
Excellent: GPA $\ge$ 8.0
Good: 6.5 $\le$ GPA < 8.0
Average: 5.0 $\le$ GPA < 6.5
Weak: GPA < 5.0
Print the result: Student [Name]: GPA = [Value], Rank: [Rank]
Find and print the name of the student with the highest GPA.
Review Questions
21.1 Which of the following is the correct syntax to declare a Dictionary?
A. info = ["name", "An", "age", 15]
B. info = ("name": "An", "age": 15)
C. info = {"name": "An", "age": 15}
D. info = {"name"; "An"; "age"; 15}
21.2 Which method is used to remove all elements from a Dictionary, leaving it empty?
A. pop()
B. clear()
C. del
D. remove()
21.3 Consider the following code:
Python
stock = {"apple": 10, "orange": 5}
stock["grape"] = 20
stock["apple"] = 15
What will the stock dictionary contain after execution?
A. {"apple": 10, "orange": 5, "grape": 20}
B. {"apple": 15, "orange": 5, "grape": 20}
C. {"apple": 10, "orange": 5, "apple": 15, "grape": 20}
D. Python raises an error because the key "apple" already exists.