Skip to main content

Bài 11 - Python Dictionary (Từ Điển)

I. Giới Thiệu

dictionary phát âm /ˈdɪk.ʃən.er.i/ - dịch ra tiếng việt là từ điển. Ở đây bạn có thể liên tưởng ngay tới cặp từ ví dụ: english : tiếng anh. Trong Python dictionary là một kiểu dữ liệu có cấu trúc tương tự là một cặp key-value. Trong ví dụ english : tiếng anh thì english là key còn tiếng anh là value. 

Dictionary (từ điển) là cấu trúc dữ liệu key-value mạnh mẽ trong Python:

  • Key: Bất biến (string, số, tuple), duy nhất
  • Value: Bất kỳ kiểu dữ liệu nào (kể cả list, dict khác)
  • Đặc điểm: Không sắp xếp thứ tự (tới Python 3.7+ giữ thứ tự chèn)

# Ví dụ mô tả sinh viên
student = {
   "name": "Alice",
   "age": 21,
   "courses": ["Math", "CS"],
   "gpa": 3.8,
   "contact": {"email": "[email protected]", "phone": "0123456789"}
}

Các keys ở đây là "name", "age", "courses", "gpa", "contact"

II. Tạo Dictionary

1. Cú pháp cơ bản

empty_dict = {}

person = {"name": "Bob", "age": 30}

2. Dùng dict() constructor

coordinates = dict(x=10, y=20)  # {'x': 10, 'y': 20}

3. Từ danh sách cặp key-value

pairs = [("a", 1), ("b", 2)]

dict_from_list = dict(pairs)  # Sẽ tạo ra dictionary {'a': 1, 'b': 2}

4. Dictionary Comprehension

squares = {x: x*x for x in range(1,6)} # {1:1, 2:4, 3:9, 4:16, 5:25}

III. Truy Cập & Thao Tác Dữ Liệu

1. Truy cập giá trị

name = student["name"]  # "Alice" → KeyError nếu key không tồn tại

age = student.get("age")  # 21 → Trả về None nếu không có

email = student.get("email", "N/A")  # "N/A" nếu key không tồn tại

2. Thêm/Thay đổi phần tử

student["graduated"] = False  # Thêm mới

student["age"] = 22  # Cập nhật giá trị

3. Xóa phần tử

del student["contact"]  # Xóa key "contact"

gpa = student.pop("gpa")  # Xóa và trả về giá trị

student.clear()  # Xóa tất cả

IV. Phương Thức Quan Trọng

MethodMô TảVí Dụ
keys()Trả về danh sách keystudent.keys() → dict_keys(['name', 'age', ...])
values()Trả về danh sách valuestudent.values() → dict_values(['Alice', 21, ...])
items()Trả về cặp (key, value)student.items() → dict_items([('name','Alice'), ...])
update()Cập nhật nhiều key-valuestudent.update({"age":23, "scholarship":True})
setdefault()Lấy giá trị hoặc tạo mớistudent.setdefault("status", "active")

V. Duyệt Dictionary

1. Duyệt qua keys

for key in student:    print(key, "→", student[key])

2. Duyệt qua items (hiệu quả)

for key, value in student.items():    print(f"{key}: {value}")

3. Duyệt có điều kiện

# In key có value là list
for key, val in student.items():
   if isinstance(val, list):
       print(f"{key} has {len(val)} items")

VI. Dictionary Lồng Nhau

1. Truy cập dữ liệu lồng

email = student["contact"]["email"]  # "[email protected]"

2. Cập nhật dữ liệu lồng

student["contact"]["phone"] = "0987654321"

3. Xử lý an toàn

# Kiểm tra tồn tại trước khi truy cập
if "contact" in student and "email" in student["contact"]:
   print(student["contact"]["email"])
   
# Hoặc dùng .get() chuỗi
phone = student.get("contact", {}).get("phone", "N/A")

VII. Ứng Dụng Thực Tế

1. Đếm tần suất phần tử

text = "hello world"
freq = {}
for char in text:
   freq[char] = freq.get(char, 0) + 1
# {'h':1, 'e':1, 'l':3, 'o':2, ...}

2. Chuyển đổi dữ liệu

# Danh sách → Dictionary
students = [("id", 101), ("name", "Alice")]
student_dict = {key: value for key, value in students}

3. Cache đơn giản

cache = {}

def expensive_calculation(n):
   if n not in cache:
       print("Calculating...")
       result = n * n  # Giả sử tính toán phức tạp
       cache[n] = result
   return cache[n]

VIII. Best Practices

1. Chọn key phù hợp

  • Dùng key mô tả rõ ràng: student_id thay vì id
  • Tránh key phức tạp: Ưu tiên string/ số thay vì tuple

2. Xử lý KeyError

# Thay vì if key in my_dict:    value = my_dict[key] # Dùng value = my_dict.get(key, default_value)

3. Merge dictionary (Python 3.9+)

dict1 = {"a": 1, "b": 2} dict2 = {"b": 3, "c": 4} merged = dict1 | dict2  # {'a':1, 'b':3, 'c':4}

4. Dùng defaultdict cho giá trị mặc định

from collections import defaultdict word_count = defaultdict(int)  # Mặc định 0 word_count["hello"] += 1

IX. Hiệu Suất & Độ Phức Tạp

OperationĐộ Phức TạpVí Dụ
Truy cậpO(1)dict[key]
Chèn/XóaO(1)dict[new] = value
DuyệtO(n)for key in dict:
Kiểm tra tồn tạiO(1)key in dict

Lưu ý: Dictionary tối ưu bộ nhớ khi có ít nhất 1/3 slot trống

X. Bài Tập Thực Hành

1. Đảo ngược dictionary (giả sử value duy nhất)

original = {"a": 1, "b": 2, "c": 3} reversed_dict = {v: k for k, v in original.items()}

2. Kết hợp dữ liệu từ nhiều nguồn

names = {101: "Alice", 102: "Bob"} scores = {101: 85, 102: 92} report = {id: {"name": names[id], "score": scores[id]} for id in names}

3. Tìm điểm chung của 2 dictionary

dict1 = {"a":1, "b":2, "c":3} 

dict2 = {"b":2, "c":4, "d":5} 

common = {k: (dict1[k], dict2[k]) for k in dict1 if k in dict2}

Tài Nguyên:

# Code mẫu đếm từ trong văn bản
def word_count(text):
   count = {}
   for word in text.split():
       count[word] = count.get(word, 0) + 1
   return count