indices必须是整数

indices必须是整数

本文介绍了TypeError:string indices必须是整数,而不是str //使用dict的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试定义一个程序,涉及(课程,人),它将输入课程结构和一个人,并返回一个描述所有课程的词典

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.

这是我的涉及(课程,人) function:

Here is my involved(courses, person) function:

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

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

When I'm trying to test my code:

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

Python给我一个错误:

Python give me an error:

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

如何解决?

谢谢。

推荐答案

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

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.

这篇关于TypeError:string indices必须是整数,而不是str //使用dict的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 07:39