python - Why doesn't this method for looping through a dictionary work -


i have dictionary within dictionary. trying return innermost dictionary ie 1 keys name, teacher etc. loop through tried this.

courses = { 'feb2012': { 'cs101': {'name': 'building search engine',                        'teacher': 'dave',                        'assistant': 'peter c.'},              'cs373': {'name': 'programming robotic car',                        'teacher': 'sebastian',                        'assistant': 'andy'}},     'jan2044': { 'cs001': {'name': 'building quantum holodeck',                        'teacher': 'dorina'},            'cs003': {'name': 'programming robotic robotics teacher',                        'teacher': 'jasper'},                  } }  e in courses:      y in e:          return courses[e][y] 

the console returns key error, doing wrong?

if do:

for e in courses:     print e 

you'd find prints "feb2012", "jan2044" -- values strings.

so for y in e: on next line iterates through characters of strings.

you meant

for e in cources:     y in cources[e]:         return courses[e][y] 

however, because return there, you'll ever find 1 of inner dictionaries. wonder if that's need.

to of them, 1 of ways make generator, yield instead of return:

def get_inner(courses):     e in courses:         y in courses[e]:  # aside, these variable names horrible             yield courses[e][y] 

and loop through them for innerdict in get_inner(courses): ....

but there many ways...


Comments