Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Định nghĩa Dictionary lồng nhau (dict trong dict) trong Python

Dictionary mutable → value của key có thể là dict khác → tạo nested dictionary.

Ví dụ

students = {
    "student1": {
        "name": "Raaj",
        "age": 23,
        "subjects": ["Phy", "Che", "maths"],
        "GPA": 8.5
    },
    "student2": {
        "name": "Kiran",
        "age": 21,
        "subjects": ["Phy", "Che", "bio"],
        "GPA": 8.25
    }
}

Truy cập & thao tác

# Đọc
students["student1"]["name"]           # 'Raaj'
students["student2"]["subjects"][2]    # 'bio'

# Thêm field
students["student1"]["email"] = "raaj@example.com"

# Thêm student mới
students["student3"] = {"name": "New", "age": 20}

# Xóa
del students["student1"]["age"]