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

การสร้าง Dictionary ภายใน Dictionary ใน Python (Nested Dict)

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["student1"]["GPA"] = 9.0
>>> students["student1"]["email"] = "raaj@example.com"

การวนลูป

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