Computer >> Computer tutorials >  >> Programming >> Python

How to count elements in a nested Python dictionary?


It is possible to iterate over each key value pair in a dictionary by the expression

for k,v in students.items():

Since value component of each item is itself a dictionary in nested Python dictionary, length of each sub-dictionary is len(v). Perform cumulative addition over the loop to obtain count of all elements

>>> 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}}
>>> s=0
>>> for k,v in students.items():
    s=s+len(v)


>>> s
8

A more compact representation of above will be −

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