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

前端 未结 3 475
醉酒成梦
醉酒成梦 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
    
    0 讨论(0)
  • 2020-12-14 06:34

    time1 is the key of the most outer dictionary, eg, feb2012. So then you're trying to index the string, but you can only do this with integers. I think what you wanted was:

    for info in courses[time1][course]:
    

    As you're going through each dictionary, you must add another nest.

    0 讨论(0)
  • 2020-12-14 06:34

    I see that you are looking for an implementation of the problem more than solving that error. Here you have a possible solution:

    from itertools import chain
    
    def involved(courses, person):
        courses_info = chain.from_iterable(x.values() for x in courses.values())
        return filter(lambda x: x['teacher'] == person, courses_info)
    
    print involved(courses, 'Dave')
    

    The first thing I do is getting the list of the courses and then filter by teacher's name.

    0 讨论(0)
提交回复
热议问题