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

Tạo nested Dictionary trong Python

Vì dict mutable, value của một 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

>>> students["student1"]["name"]
'Raaj'
>>> students["student2"]["subjects"][2]
'bio'

Thêm/cập nhật nested

students["student1"]["email"] = "raaj@example.com"
students["student3"] = {"name": "New", "age": 20}

Xóa

del students["student1"]["age"]
del students["student2"]