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

Đếm phần tử trong nested dictionary Python

Nested dictionary: value của key là một dictionary khác. Đếm tổng số cặp key-value ở tất cả cấp con.

Ví dụ dữ liệu

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

Cách 1: Vòng lặp for + len()

total = 0
for v in students.values():
    total += len(v)
print(total)  # 8

Cách 2: Generator expression + sum() (pythonic)

total = sum(len(v) for v in students.values())
print(total)  # 8

Đếm đệ quy (tất cả cấp độ)

def count_all(d):
    count = 0
    for v in d.values():
        if isinstance(v, dict):
            count += count_all(v)
        else:
            count += 1
    return count