Khóa học python

Nested Dictionary trong Python

0 phút đọc

Nested Dictionary trong Python là một dictionary chứa một hoặc nhiều dictionary khác bên trong nó. Điều này cho phép bạn lưu trữ và tổ chức dữ liệu phức tạp theo cấu trúc phân cấp. Nested Dictionary rất hữu ích khi bạn cần lưu trữ thông tin có cấu trúc, chẳng hạn như hồ sơ học sinh, thông tin nhân viên, hoặc dữ liệu JSON.

Tạo Nested Dictionary

Bạn có thể tạo một nested dictionary bằng cách sử dụng cặp dấu ngoặc nhọn {} hoặc hàm dict(). Dưới đây là một số ví dụ minh họa:

Ví dụ 1: Tạo Nested Dictionary bằng cặp dấu ngoặc nhọn

# Tạo một nested dictionary đơn giản
school = {
    'student1': {'name': 'John', 'age': 15, 'class': '10th'},
    'student2': {'name': 'Jane', 'age': 14, 'class': '9th'},
    'student3': {'name': 'Jim', 'age': 16, 'class': '11th'}
}
print(school)
# Output: {'student1': {'name': 'John', 'age': 15, 'class': '10th'}, 'student2': {'name': 'Jane', 'age': 14, 'class': '9th'}, 'student3': {'name': 'Jim', 'age': 16, 'class': '11th'}}

Ví dụ 2: Tạo Nested Dictionary bằng hàm dict()

# Tạo một nested dictionary bằng hàm dict()
school = dict(
    student1=dict(name='John', age=15, class_='10th'),
    student2=dict(name='Jane', age=14, class_='9th'),
    student3=dict(name='Jim', age=16, class_='11th')
)
print(school)
# Output: {'student1': {'name': 'John', 'age': 15, 'class_': '10th'}, 'student2': {'name': 'Jane', 'age': 14, 'class_': '9th'}, 'student3': {'name': 'Jim', 'age': 16, 'class_': '11th'}}

Truy cập phần tử trong Nested Dictionary

Bạn có thể truy cập các phần tử trong một nested dictionary bằng cách sử dụng chỉ số (index) hoặc key.

Ví dụ 3: Truy cập phần tử bằng key

school = {
    'student1': {'name': 'John', 'age': 15, 'class': '10th'},
    'student2': {'name': 'Jane', 'age': 14, 'class': '9th'},
    'student3': {'name': 'Jim', 'age': 16, 'class': '11th'}
}

# Truy cập thông tin của student1
print(school['student1']['name'])  # Output: John
print(school['student1']['age'])   # Output: 15
print(school['student1']['class']) # Output: 10th

Thêm và cập nhật phần tử trong Nested Dictionary

Bạn có thể thêm hoặc cập nhật các phần tử trong một nested dictionary bằng cách sử dụng key và gán giá trị mới.

Ví dụ 4: Thêm phần tử mới

school = {
    'student1': {'name': 'John', 'age': 15, 'class': '10th'},
    'student2': {'name': 'Jane', 'age': 14, 'class': '9th'}
}

# Thêm student3 vào dictionary
school['student3'] = {'name': 'Jim', 'age': 16, 'class': '11th'}
print(school)
# Output: {'student1': {'name': 'John', 'age': 15, 'class': '10th'}, 'student2': {'name': 'Jane', 'age': 14, 'class': '9th'}, 'student3': {'name': 'Jim', 'age': 16, 'class': '11th'}}

Ví dụ 5: Cập nhật phần tử hiện có

school = {
    'student1': {'name': 'John', 'age': 15, 'class': '10th'},
    'student2': {'name': 'Jane', 'age': 14, 'class': '9th'}
}

# Cập nhật thông tin của student1
school['student1']['age'] = 16
print(school)
# Output: {'student1': {'name': 'John', 'age': 16, 'class': '10th'}, 'student2': {'name': 'Jane', 'age': 14, 'class': '9th'}}

Xoá phần tử trong Nested Dictionary

Python cung cấp nhiều phương thức để xoá phần tử khỏi dictionary, bao gồm del, pop(), và clear().

Ví dụ 6: Sử dụng từ khoá del

school = {
    'student1': {'name': 'John', 'age': 15, 'class': '10th'},
    'student2': {'name': 'Jane', 'age': 14, 'class': '9th'}
}

# Xoá student1 khỏi dictionary
del school['student1']
print(school)
# Output: {'student2': {'name': 'Jane', 'age': 14, 'class': '9th'}}

Ví dụ 7: Sử dụng hàm pop()

school = {
    'student1': {'name': 'John', 'age': 15, 'class': '10th'},
    'student2': {'name': 'Jane', 'age': 14, 'class': '9th'}
}

# Xoá và trả về giá trị của student1
student1 = school.pop('student1')
print(student1)  # Output: {'name': 'John', 'age': 15, 'class': '10th'}
print(school)    # Output: {'student2': {'name': 'Jane', 'age': 14, 'class': '9th'}}

Ví dụ 8: Sử dụng hàm clear()

school = {
    'student1': {'name': 'John', 'age': 15, 'class': '10th'},
    'student2': {'name': 'Jane', 'age': 14, 'class': '9th'}
}

# Xoá tất cả các phần tử trong dictionary
school.clear()
print(school)  # Output: {}

Duyệt qua các phần tử trong Nested Dictionary

Bạn có thể sử dụng vòng lặp for để duyệt qua các phần tử trong một nested dictionary.

Ví dụ 9: Sử dụng vòng lặp for

school = {
    'student1': {'name': 'John', 'age': 15, 'class': '10th'},
    'student2': {'name': 'Jane', 'age': 14, 'class': '9th'}
}

# Duyệt qua các phần tử trong nested dictionary
for student, info in school.items():
    print(f"Student: {student}")
    for key, value in info.items():
        print(f"  {key}: {value}")
# Output:
# Student: student1
#   name: John
#   age: 15
#   class: 10th
# Student: student2
#   name: Jane
#   age: 14
#   class: 9th

Sử dụng Dictionary Comprehension với Nested Dictionary

Dictionary comprehension là một cách ngắn gọn và hiệu quả để tạo dictionary mới từ dictionary hiện có.

Ví dụ 10: Dictionary Comprehension

school = {
    'student1': {'name': 'John', 'age': 15, 'class': '10th'},
    'student2': {'name': 'Jane', 'age': 14, 'class': '9th'}
}

# Tạo dictionary mới với tuổi của học sinh tăng thêm 1
new_school = {student: {k: (v + 1 if k == 'age' else v) for k, v in info.items()} for student, info in school.items()}
print(new_school)
# Output: {'student1': {'name': 'John', 'age': 16, 'class': '10th'}, 'student2': {'name': 'Jane', 'age': 15, 'class': '9th'}}

Kết luận

Nested Dictionary là một cấu trúc dữ liệu mạnh mẽ và linh hoạt trong Python, cho phép bạn lưu trữ và tổ chức dữ liệu phức tạp theo cấu trúc phân cấp. Việc hiểu và sử dụng các phương thức và hàm của nested dictionary sẽ giúp bạn làm việc hiệu quả hơn với loại dữ liệu này. Hy vọng bài viết này đã cung cấp cho bạn một cái nhìn tổng quan và chi tiết về cách tạo, truy cập, thêm, cập nhật, xoá và duyệt qua các phần tử của nested dictionary trong Python.

Avatar
Được viết bởi

TechMely Team

Gợi ý câu hỏi phỏng vấn

Gợi ý bài viết

Bình luận

Chưa có bình luận nào

Khoá học javascript từ cơ bản đến chuyên sâuYoutube Techmely