TypeError: string indices must be integers, not str - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Homework (https://python-forum.io/forum-9.html) +--- Thread: TypeError: string indices must be integers, not str (/thread-1484.html) |
TypeError: string indices must be integers, not str - hanieh - Jan-06-2017 Hi, I have a piece of code with the following type error: I am new to Python and got stuck in my code. Would you please help me figure out whats the problem?Many thanks alice = { "name": "Alice", "homework": [100.0, 92.0, 98.0, 100.0], "quizzes": [82.0, 83.0, 91.0], "tests": [89.0, 97.0] } tyler = { "name": "Tyler", "homework": [0.0, 87.0, 75.0, 22.0], "quizzes": [0.0, 75.0, 78.0], "tests": [100.0, 100.0] } def get_average(student): homework = 0 quizzes = 0 tests = 0 for key in student: homework =sum(key["homework"])/len(key["homework"]) quizzes = sum(key["quizzes"])/len(key["quizzes"]) tests = sum(key["tests"])/len(key["tests"]) res = 0.1 * homework + 0.3 * quizzes + 0.6 * tests print key["name"], float(res) student = [alice,tyler] get_average(student) RE: TypeError: string indices must be integers, not str - Yoriz - Jan-06-2017 Please use the forums bbcode tags. The code shown does not report the error shown, Please show matching code to error traceback. RE: TypeError: string indices must be integers, not str - Ofnuts - Jan-08-2017 Your key variable is a string, so key["name"] is indeed trying to index a string with another string. Perhaps you want student["name"] . But it is not clear why you want to iterate on the keys...
RE: TypeError: string indices must be integers, not str - buran - Jan-08-2017 @Ofnuts actually in the above code student is list of dicts, so key is a dict. Yoritz is correct that the above code is not the one that produce this error. However due to the incorect indentation it prints only the last name, res pair.
RE: TypeError: string indices must be integers, not str - delonbest - Jan-04-2021 TypeError: means that you are trying to perform an operation on a value whose type is not compatible with that operation. If you are accessing items from a dictionary , make sure that you are accessing the dictionary itself and not a key in the dictionary. TypeError: string indices must be integers has been caused because you are trying to access values from dictionary using string indices instead of integer. |