我正在尝试定义一个程序involved(courses, person)
,该程序将课程结构和人员作为输入,并返回一个描述该人参与的所有课程的词典。
这是我的involved(courses, person)
功能:
def involved(courses, person):
for time1 in courses:
for course in courses[time1]:
for info in time1[course]:
print info
这是我的字典:
courses = {
'feb2012': { 'cs101': {'name': 'Building a Search Engine',
'teacher': 'Dave',
'assistant': 'Peter C.'},
'cs373': {'name': 'Programming a Robotic Car',
'teacher': 'Sebastian',
'assistant': 'Andy'}},
'apr2012': { 'cs101': {'name': 'Building a Search Engine',
'teacher': 'Dave',
'assistant': 'Sarah'},
'cs212': {'name': 'The Design of Computer Programs',
'teacher': 'Peter N.',
'assistant': 'Andy',
'prereq': 'cs101'},
'cs253':
{'name': 'Web Application Engineering - Building a Blog',
'teacher': 'Steve',
'prereq': 'cs101'},
'cs262':
{'name': 'Programming Languages - Building a Web Browser',
'teacher': 'Wes',
'assistant': 'Peter C.',
'prereq': 'cs101'},
'cs373': {'name': 'Programming a Robotic Car',
'teacher': 'Sebastian'},
'cs387': {'name': 'Applied Cryptography',
'teacher': 'Dave'}},
'jan2044': { 'cs001': {'name': 'Building a Quantum Holodeck',
'teacher': 'Dorina'},
'cs003': {'name': 'Programming a Robotic Robotics Teacher',
'teacher': 'Jasper'},
}
}
当我尝试测试我的代码时:
>>>print involved(courses, 'Dave')
Python给我一个错误:
for info in time1[course]:
TypeError: string indices must be integers, not str
我该如何解决?
感谢。
答案 0 :(得分:33)
time1
是最外层字典的关键,例如feb2012
。那么你试图索引字符串,但你只能用整数来做。我想你想要的是:
for info in courses[time1][course]:
当你浏览每个字典时,你必须添加另一个字符串。
答案 1 :(得分:8)
实际上我认为循环字典的更一般方法是使用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
输出:
assistant Peter C.
prereq cs101
...
name Programming a Robotic Car
teacher Sebastian
或者,正如Matthias在评论中提到的,如果您不需要密钥,则可以使用itervalues():
for term_courses in courses.itervalues():
for info in term_courses.itervalues():
for k, v in info.iteritems():
print k, v
答案 2 :(得分:-1)
我发现您正在寻找问题的实现而不是解决该错误。在这里你有一个可能的解决方案:
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')
我要做的第一件事就是获取课程列表,然后按老师的名字过滤。