Python 类型错误:字符串索引必须是整数,而不是 str // 使用 dict

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18931315/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:17:51  来源:igfitidea点击:

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

pythondictionary

提问by Michael

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 the courses the person is involved in.

我正在尝试定义一个过程,involved(courses, person)它将课程结构和一个人作为输入,并返回一个描述该人参与的所有课程的字典。

Here is my involved(courses, person)function:

这是我的involved(courses, person)功能:

def involved(courses, person):
    for time1 in courses:
        for course in courses[time1]:
            for info in time1[course]:
                print info

Here is my dictionary:

这是我的字典:

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'},
                     }
    }

When I'm trying to test my code:

当我尝试测试我的代码时:

>>>print involved(courses, 'Dave')

Python give me an error:

Python给我一个错误:

for info in time1[course]:
TypeError: string indices must be integers, not str

How can I fix that?

我该如何解决?

Thanks.

谢谢。

采纳答案by TerryA

time1is 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:

time1是最外层字典的键,例如,feb2012。那么你试图索引字符串,但你只能用整数来做到这一点。我想你想要的是:

for info in courses[time1][course]:

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

当您浏览每本词典时,您必须添加另一个嵌套。

回答by Roman Pekar

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

实际上,我认为循环字典的更一般方法是使用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():

或者,正如 Matthias 在评论中提到的,如果你不需要键,你可以只使用itervalues()

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

回答by moliware

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.

我做的第一件事是获取课程列表,然后按教师姓名进行过滤。