Từ điển (Dictionary)
1. Dictionary là gì?
Dictionary là một cấu trúc dữ liệu cho phép lưu trữ các cặp key-value (khoá-giá trị). Hãy tưởng tượng nó giống như một cuốn từ điển thật:
- Key (khoá) là từ bạn cần tra
- Value (giá trị) là nghĩa của từ đó
Dictionary có những đặc điểm sau:
- Có thể thay đổi (mutable): Bạn có thể thêm, sửa, xoá các phần tử
- Không có thứ tự cố định (từ Python 3.7+ thì giữ thứ tự thêm vào)
- Key phải là duy nhất: Không có hai key giống nhau
Ví dụ dictionary hợp lệ:
student = {
"name": "Minh Anh",
"age": 10,
"grade": 5
}
fruits_price = {
"apple": 15000,
"banana": 10000,
"orange": 20000
}2. Cách tạo Dictionary
Tạo dictionary bằng cặp ngoặc nhọn
student = {
"name": "Tuệ Nghi",
"age": 11,
"school": "Trường Tiểu học ABC"
}scores = {
"math": 9.5,
"literature": 8.0,
"english": 9.0
}Tạo một dictionary rỗng
empty_dict = {}
another_empty_dict = dict()Tạo dictionary bằng hàm dict()
student = dict(name="Bảo Nguyên", age=10, grade=5)
# Kết quả: {"name": "Bảo Nguyên", "age": 10, "grade": 5}3. Các thao tác cơ bản với Dictionary
Lấy số lượng cặp key-value
student = {"name": "Phước Sâm", "age": 11, "grade": 5}
len(student) # 3Truy cập giá trị theo key
student = {"name": "Minh Sang", "age": 10}
# Cách 1: Dùng dấu ngoặc vuông []
print(student["name"]) # "Minh Sang"
# Cách 2: Dùng phương thức get()
print(student.get("age")) # 10Lưu ý: Nếu key không tồn tại:
- Dùng
[]sẽ gây lỗi - Dùng
get()sẽ trả vềNonehoặc giá trị mặc định
student = {"name": "Đức Sơn"}
# print(student["age"]) # Lỗi! Không có key "age"
print(student.get("age")) # None
print(student.get("age", 0)) # 0 (giá trị mặc định)Kiểm tra key có trong dictionary không
student = {"name": "Bảo Đăng", "age": 11}
if "name" in student:
print("Có thông tin tên")
if "phone" not in student:
print("Không có số điện thoại")Thêm hoặc thay đổi giá trị
student = {"name": "Hồng Phúc", "age": 10}
# Thêm key mới
student["grade"] = 5
print(student) # {"name": "Hồng Phúc", "age": 10, "grade": 5}
# Thay đổi giá trị của key đã có
student["age"] = 11
print(student) # {"name": "Hồng Phúc", "age": 11, "grade": 5}Xoá phần tử
student = {"name": "Gia Hưng", "age": 10, "grade": 5}
# Xoá theo key bằng del
del student["grade"]
print(student) # {"name": "Gia Hưng", "age": 10}
# Xoá và lấy giá trị bằng pop()
age = student.pop("age")
print(age) # 10
print(student) # {"name": "Gia Hưng"}4. Các phương thức quan trọng của Dictionary
| Phương thức | Chức năng | Ví dụ |
|---|---|---|
get(key) | Lấy giá trị của key | student.get("name") |
keys() | Lấy tất cả các key | student.keys() |
values() | Lấy tất cả các value | student.values() |
items() | Lấy tất cả cặp key-value | student.items() |
update(dict2) | Cập nhật từ dictionary khác | student.update({"age": 11}) |
pop(key) | Xoá và trả về giá trị của key | student.pop("age") |
clear() | Xoá toàn bộ dictionary | student.clear() |
copy() | Tạo bản sao | new_dict = student.copy() |
Ví dụ: student = {"name": "Hoàng Thịnh", "age": 10, "grade": 5}
1. get(key) - Lấy giá trị của key
student = {"name": "Hoàng Thịnh", "age": 10, "grade": 5}
name = student.get("name")
print(name) # "Hoàng Thịnh"
# Có thể đặt giá trị mặc định nếu key không tồn tại
phone = student.get("phone", "Chưa có")
print(phone) # "Chưa có"2. keys() - Lấy tất cả các key
student = {"name": "Trọng Phát", "age": 11, "grade": 5}
keys = student.keys()
print(keys) # dict_keys(["name", "age", "grade"])
print(list(keys)) # ["name", "age", "grade"]3. values() - Lấy tất cả các value
student = {"name": "Tuệ Nghi", "age": 10, "grade": 5}
values = student.values()
print(values) # dict_values(["Tuệ Nghi", 10, 5])
print(list(values)) # ["Tuệ Nghi", 10, 5]4. items() - Lấy tất cả cặp key-value
student = {"name": "Minh Sang", "age": 11}
items = student.items()
print(items) # dict_items([("name", "Minh Sang"), ("age", 11)])5. update(dict2) - Cập nhật từ dictionary khác
student = {"name": "Phước Sâm", "age": 10}
student.update({"grade": 5, "school": "ABC"})
print(student)
# {"name": "Phước Sâm", "age": 10, "grade": 5, "school": "ABC"}
# Cũng có thể cập nhật giá trị đã có
student.update({"age": 11})
print(student) # age đã đổi thành 116. pop(key) - Xoá và trả về giá trị
student = {"name": "Bảo Nguyên", "age": 10, "grade": 5}
age = student.pop("age")
print(age) # 10
print(student) # {"name": "Bảo Nguyên", "grade": 5}7. clear() - Xoá toàn bộ dictionary
student = {"name": "Đức Sơn", "age": 11}
student.clear()
print(student) # {}8. copy() - Tạo bản sao
student1 = {"name": "Bảo Đăng", "age": 10}
student2 = student1.copy()
student2["age"] = 11
print(student1) # {"name": "Bảo Đăng", "age": 10} - không bị thay đổi
print(student2) # {"name": "Bảo Đăng", "age": 11}5. Duyệt Dictionary bằng vòng lặp for
5.1 - Duyệt qua các key
student = {"name": "Hồng Phúc", "age": 10, "grade": 5}
for key in student:
print(key)
# name
# age
# gradeHoặc dùng keys():
for key in student.keys():
print(key)5.2 - Duyệt qua các value
student = {"name": "Gia Hưng", "age": 11, "grade": 5}
for value in student.values():
print(value)
# Gia Hưng
# 11
# 55.3 - Duyệt qua cả key và value
student = {"name": "Hoàng Thịnh", "age": 10, "grade": 5}
for key, value in student.items():
print(f"{key}: {value}")
# name: Hoàng Thịnh
# age: 10
# grade: 56. Dictionary lồng nhau (Nested Dictionary)
Dictionary có thể chứa dictionary khác bên trong:
students = {
"student1": {
"name": "Trọng Phát",
"age": 10,
"grade": 5
},
"student2": {
"name": "Tuệ Nghi",
"age": 11,
"grade": 5
}
}
# Truy cập thông tin
print(students["student1"]["name"]) # "Trọng Phát"
print(students["student2"]["age"]) # 117. Ví dụ thực tế
Ví dụ 1: Sổ điểm học sinh
scores = {
"math": 9.5,
"literature": 8.0,
"english": 9.0,
"science": 8.5
}
# Tính điểm trung bình
total = sum(scores.values())
average = total / len(scores)
print(f"Điểm trung bình: {average}")Ví dụ 2: Đếm số lần xuất hiện của từ
text = "python is fun python is easy"
words = text.split()
word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
print(word_count)
# {"python": 2, "is": 2, "fun": 1, "easy": 1}Ví dụ 3: Danh bạ điện thoại
phonebook = {
"Minh Sang": "0901234567",
"Phước Sâm": "0907654321",
"Bảo Nguyên": "0909876543"
}
# Tìm số điện thoại
name = "Minh Sang"
if name in phonebook:
print(f"Số điện thoại của {name}: {phonebook[name]}")
else:
print("Không tìm thấy")8. So sánh Dictionary và List
| Đặc điểm | List | Dictionary |
|---|---|---|
| Cấu trúc | Danh sách có thứ tự | Cặp key-value |
| Truy cập | Dùng index (số) | Dùng key |
| Thứ tự | Có thứ tự rõ ràng | Giữ thứ tự thêm vào (Python 3.7+) |
| Tìm kiếm | Chậm hơn | Nhanh hơn |
| Dùng khi nào | Lưu danh sách các phần tử | Lưu thông tin có thuộc tính |
Bài giảng trên YouTube
(Cập nhật sau)