7.1 Tạo dictionary lồng nhau
Dictionary lồng nhau là một cách rất tiện lợi để miêu tả cấu trúc dữ liệu phức tạp mà bạn sẽ gặp rất thường xuyên. Hãy cùng thực hành một chút về cách tạo chúng.
Tạo dictionary lồng nhau
Đây là ví dụ về cách tạo dictionary lồng nhau:
person = {
"name": "Alice",
"details": {
"age": 25,
"city": "New York",
"address": {
"street": "123 Main St",
"zip": "10001"
},
"mother": "Jane Smith"
},
"gender": "female"
}
print(person) # Kết quả: {'name': 'Alice', 'details': {'age': 25, 'city': 'New York', 'address': {'street': '123 Main St', 'zip': '10001'}, 'mother': 'Jane Smith'}, 'gender': 'female'}
Trong ví dụ này, person là một dictionary chứa một dictionary lồng bên trong details, mà bản thân nó cũng chứa một dictionary lồng khác address.
Dictionary lồng nhau có thể được tạo từ những mảnh nhỏ:
address = {
"street": "123 Main St",
"zip": "10001"
}
details = {
"age": 25,
"city": "New York",
"address": address
}
person = {
"name": "Alice",
"details": details,
"gender": "female"
}
print(person) # Kết quả: {'name': 'Alice', 'details': {'age': 25, 'city': 'New York', 'address': {'street': '123 Main St', 'zip': '10001'}}, 'gender': 'female'}
7.2 Truy cập phần tử của dictionary lồng nhau
Truy cập vào phần tử của dictionary lồng nhau rất đơn giản và rõ ràng. Đây là cách làm:
Truy cập đến phần tử cấp cao
name = person["name"]
print(name) # Kết quả: Alice
Truy cập vào phần tử của dictionary lồng nhau
age = person["details"]["age"]
city = person["details"]["city"]
print(age) # Kết quả: 25
print(city) # Kết quả: New York
Truy cập vào các phần tử tầng sâu hơn
street = person["details"]["address"]["street"]
zip_code = person["details"]["address"]["zip"]
print(street) # Kết quả: 123 Main St
print(zip_code) # Kết quả: 10001
7.3 Thay đổi phần tử của dictionary lồng nhau
Nếu bạn đã hiểu cách để xuất các phần tử ở mọi mức độ lồng nhau, thì việc thay đổi chúng sẽ còn đơn giản hơn nữa:
Thay đổi giá trị của cấp cao
person["name"] = "Bob"
print(person["name"]) # Kết quả: Bob
Thay đổi giá trị của dictionary lồng nhau
person["details"]["age"] = 26
print(person["details"]["age"]) # Kết quả: 26
Thay đổi giá trị của các tầng sâu hơn
person["details"]["address"]["city"] = "Los Angeles"
print(person["details"]["address"]["city"]) # Kết quả: Los Angeles
Thêm phần tử mới vào dictionary lồng nhau
person["details"]["phone"] = "123-456-7890"
print(person["details"]["phone"]) # Kết quả: 123-456-7890
Xóa phần tử cấp cao
# Xóa phần tử 'country' khỏi dictionary 'person'
del person["country"]
print(person) # Phần tử 'country' sẽ bị xóa khỏi dictionary
Xóa phần tử từ dictionary lồng nhau
# Xóa phần tử 'phone' khỏi dictionary 'details'
del person["details"]["phone"]
print(person["details"]) # Phần tử 'phone' sẽ bị xóa khỏi dictionary 'details'
7.4 Duyệt qua dictionary lồng nhau
Có vài cách để duyệt qua tất cả các phần tử của một dictionary. Sử dụng vòng lặp là cách đơn giản nhất:
Iterator qua các phần tử của dictionary lồng nhau
for key, value in person.items(): # Duyệt qua dictionary cha
if isinstance(value, dict): # Nếu giá trị là một dictionary
for key2, value2 in value.items(): # Duyệt qua các phần tử của dictionary con
print(f"{key} --> {key2}: {value2}")
Duyệt đệ quy qua mọi cấp độ lồng nhau
def print_dict(d, indent=0):
for key, value in d.items():
print(" " * indent + str(key) + ": ", end="")
if isinstance(value, dict):
print()
print_dict(value, indent + 1)
else:
print(value)
print_dict(person)
Chi tiết hơn về đệ quy sẽ được trình bày trong chủ đề «Thuật toán và Cấu trúc dữ liệu».
Nhân tiện, đệ quy rất tiện lợi để tìm kiếm giá trị sâu bên trong dictionary lồng nhau. Đây là một ví dụ:
def find_key(d, key):
if key in d:
return d[key]
for k, v in d.items():
if isinstance(v, dict):
result = find_key(v, key)
if result:
return result
return None
phone = find_key(person, "phone")
print(phone) # Kết quả: None (vì phần tử 'phone' đã bị xóa)
GO TO FULL VERSION