Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การสร้าง Nested Dictionary ใน Python

Dictionary เป็น mutable → สามารถใช้ Dictionary อีกตัวหนึ่งเป็น Value ของ Key ได้ → สร้าง Nested Dictionary

ตัวอย่าง

>> 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
...     }
... }
>>> 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}}

การเข้าถึงข้อมูล

>> students["student1"]["name"]
'Raaj'
>>> students["student2"]["subjects"]
['Phy', 'Che', 'bio']

การเพิ่ม/แก้ไขข้อมูล

>> # เพิ่มนักเรียนใหม่
>>> students["student3"] = {"name": "Amit", "age": 22, "subjects": ["Math", "CS"], "GPA": 9.0}

>>> # แก้ไขข้อมูลซ้อน
>>> students["student1"]["GPA"] = 9.0

>>> # เพิ่มฟิลด์ใหม่ใน sub-dict
>>> students["student1"]["email"] = "raaj@example.com"

การวนลูป Nested Dictionary

>> for student_id, info in students.items():
...     print(f"{student_id}: {info['name']}, Age: {info['age']}, GPA: {info['GPA']}")
student1: Raaj, Age: 23, GPA: 8.5
student2: Kiran, Age: 21, GPA: 8.25