![]() |
TypeError: string indices must be integers - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: TypeError: string indices must be integers (/thread-13129.html) |
TypeError: string indices must be integers - saladgg - Sep-29-2018 Am learning to create a python API. I want to get a return a student object whenever there's a match of student name when I loop through the students data. Please tell me what I am doing wrong. I get the error TypeError: string indices must be integers class Student(Resource): #get student by name def get(self, name): for student in students: if name == student["name"]: return student, 200 return "student not found", 404 RE: TypeError: string indices must be integers - Larz60+ - Sep-29-2018 name = '404' would be a string, name = 404 an integer. It's requesting an integer, not string. when in doubt, you can find out what the type is with print(type(name)) RE: TypeError: string indices must be integers - saladgg - Sep-30-2018 I may have left out some important info. I am using firebase realtime db. This solved my problem. I was supposed to loop through by means of key,value. class Student(Resource): dbStudents = db.reference("/students") students = dbStudents.get() def get(self, name): for key, value in students.items(): if name == value["name"]: return value, 200 return "student not found", 404 RE: TypeError: string indices must be integers - buran - Oct-01-2018 it looks you are getting a dict, so you can do for student in students.values(): if name == student["name"]: return student, 200Now, the question is why you don't filter the result set from the db in the first place? RE: TypeError: string indices must be integers - saladgg - Oct-03-2018 @burah, that works fine too. ![]() |