Home > Back-end >  iterating nested dictionaries using for loop in python
iterating nested dictionaries using for loop in python

Time:10-15

here is my json file which has sample data in nested dictionaries like below

data = {
    'school': {
        'name': 'abc',
        'class': {
            'firstclass': {'teacher': 'b', 'students': '10'},
            'secondclass': {'teacher': 'c', 'students': '25'},
        }, 'city': 'x'},
    'college': {
        'name': 'def',
        'class': {
            'firstclass': {'teacher': 'd', 'students': '9'},
            'secondclass': {'teacher': 'e', 'students': '65'},
        }, 'city': 'y'},
    'university': {
        'name': 'ghi',
        'class': {
            'firstclass': {'teacher': 'f', 'students': '55'},
            'secondclass': {'teacher': 'g', 'students': '22'},
        }, 'city': 'z'}
}

my output should be like:

'teacher':'b','students':'10'
'teacher':'c','students':'25'
'teacher':'d','students':'9'
'teacher':'e','students':'65'
'teacher':'f','students':'55'
'teacher':'g','students':'22'

here is my code in for loop:

for id in data:
    for j in data[id]:
        print(j  ,"="  , data[id][j])

i am not getting above expected output. how to get exact output as above .

CodePudding user response:

This might nudge you in the right direction:

for v in data.values():
    for dct in v["class"].values():
        print(", ".join(map("=".join, dct.items())))
    
teacher=b, students=10
teacher=c, students=25
teacher=d, students=9
teacher=e, students=65
teacher=f, students=55
teacher=g, students=22
  • Related