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

การนับจำนวนสมาชิกใน Nested Dictionary ใน Python

Nested Dictionary คือ Dictionary ที่ Value เป็น 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}
... }

วิธีที่ 1: Loop + len()

>> s = 0
>>> for k, v in students.items():
...     s += len(v)
>>> s
8

วิธีที่ 2: sum() + generator expression (Pythonic)

>> sum(len(v) for v in students.values())
8

วิธีที่ 3: นับเฉพาะ key ระดับลึก (Deep count)

หากต้องการนับ key ทุกระดับรวม nested:

>> def deep_count(d):
...     count = len(d)
...     for v in d.values():
...         if isinstance(v, dict):
...             count += deep_count(v)
...     return count

>>> deep_count(students)
10  # 2 top-level + 4+4 nested keys

หมายเหตุ: len(v) นับจำนวน key-value pairs ใน sub-dictionary แต่ละตัว