TypeError: string indices must be integers, not str // working with dict

前端 未结 3 476
醉酒成梦
醉酒成梦 2020-12-14 05:38

I am trying to define a procedure, involved(courses, person), that takes as input a courses structure and a person and returns a Dictionary that describes all t

3条回答
  •  自闭症患者
    2020-12-14 06:32

    Actually I think that more general approach to loop through dictionary is to use iteritems():

    # get tuples of term, courses
    for term, term_courses in courses.iteritems():
        # get tuples of course number, info
        for course, info in term_courses.iteritems():
            # loop through info
            for k, v in info.iteritems():
                print k, v
    

    output:

    assistant Peter C.
    prereq cs101
    ...
    name Programming a Robotic Car
    teacher Sebastian
    

    Or, as Matthias mentioned in comments, if you don't need keys, you can just use itervalues():

    for term_courses in courses.itervalues():
        for info in term_courses.itervalues():
            for k, v in info.iteritems():
                print k, v
    

提交回复
热议问题