TypeError: string indices must be integers
TypeError: string indices must be integers in Python means you used text inside square brackets on a string, like s["name"]. You probably thought the value was a dictionary, but it is a string.
How do I fix TypeError: string indices must be integers?
TypeError: string indices must be integers means you used text in square brackets on a string, like data["name"]. You expected a dictionary but have a string. Usually it is JSON text you never parsed, so call json.loads() first. Or you looped over a dictionary and got its keys, so use .items() instead.
- 1. Print with repr()Add print(type(x), repr(x)) before the failing line. JSON-looking text in quotes means it was never parsed.
- 2. Parse JSON firstUse json.loads(text), or response.json() with requests, to turn the text into a dictionary.
- 3. Check your loopfor x in some_dict gives string keys. Use for key, value in some_dict.items() to get the values.
What does TypeError: string indices must be integers mean?
A string's characters are numbered 0, 1, 2…, so the only things allowed inside the brackets are whole numbers or slices. s["name"] would only work on a dictionary. Newer Python versions add ", not 'str'" to the message. The usual causes are JSON that was never parsed, or looping over a dictionary and getting its keys.
Why does TypeError: string indices must be integers happen?
1. JSON text that was not turned into a dictionary
Text from a file or API is a string until you parse it with json.loads().
Breaks
data = '{"name": "Ada"}'
print(data["name"])Works
import json
data = json.loads('{"name": "Ada"}')
print(data["name"])2. Looping over a dictionary gives keys, not records
for x in some_dict gives each key, which is a string.
Breaks
user = {"name": "Ada", "age": 36}
for item in user:
print(item["name"])Works
user = {"name": "Ada", "age": 36}
for key, value in user.items():
print(key, value)3. Using input() as a position
input() always returns text. Convert it with int() before indexing.
Breaks
word = "python"
pos = input("Position: ")
print(word[pos])Works
word = "python"
pos = int(input("Position: "))
print(word[pos])How to find it in your own code
Checklist: 1) Find the variable before the [ on the failing line. 2) print(type(x), repr(x)). 3) If it shows JSON-looking text, parse it with json.loads() (or response.json() for requests). 4) If it came from a loop, check what you are looping over; use .items() or .values() for dictionaries. 5) Wrap user input in int() before using it as a position.
Practise type errors
None of the challenges raises this exact error yet. These practise the same kind of bug.
Still not sure why yours breaks?
Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.