TypeError: string indices must be integers, not 'str'
1 · The lesson
readWhat this error means
You wrote something["name"], and something is a string, not a dict. A string only lets you pick out characters by position: word[0] is the first letter, word[-1] is the last. So Python expected a whole number inside the square brackets and got text. The real question is why the value is a string when you thought it was a dict.
When you see it
Traceback (most recent call last): File "main.py", line 3, in <module> print(user["name"]) ~~~~^^^^^^^^ TypeError: string indices must be integers, not 'str'
The end of the message tells you what you put in the brackets. With a decimal number you get:
Traceback (most recent call last): File "main.py", line 2, in <module> print(word[len(word) / 2]) ~~~~^^^^^^^^^^^^^^^ TypeError: string indices must be integers, not 'float'
Python 3.10 and older print the shorter TypeError: string indices must be integers. It is the same error.
Why it happens
Four situations cause almost every case.
1. JSON you never parsed. Text from an API, a file or a database looks like a dict when you print it, but until you call json.loads it is one long string.
body = '{"name": "Ada", "role": "admin"}' print(body["name"]) # TypeError: not 'str'
2. Looping over a dict gives you its keys. for x in some_dict hands you each key, and the keys are strings. Indexing a key with ["name"] fails.
user = {"name": "Ada", "role": "admin"}
for item in user:
print(item["name"]) # item is "name", then "role"3. One level too deep. Nested data has a string at the bottom. If you index one more time than the data has levels, you are indexing that string.
data = {"user": {"name": "Ada"}}
name = data["user"]["name"] # "Ada"
print(name["first"]) # TypeError: "Ada" is a string4. A position that isn't a whole number. input() always returns text, so word[input()] fails with not 'str'. Normal division / always gives a float, even for 6 / 2, so word[len(word) / 2] fails with not 'float'.
How to fix it
Parse the JSON first. json.loads turns the text into a dict, and then keys work:
import json body = '{"name": "Ada", "role": "admin"}' user = json.loads(body) print(user["name"]) # Ada
With the requests library, use response.json() instead of response.text. It does the parsing for you.
Loop with .items() when you need keys and values. Or index the dict itself with the key you are given:
user = {"name": "Ada", "role": "admin"}
for key, value in user.items():
print(key, "=", value)
# name = Ada
# role = admin
for key in user:
print(user[key]) # Ada, then adminIf you actually have a list of dicts, loop over the list. Each item is then a dict:
users = [{"name": "Ada"}, {"name": "Grace"}]
for user in users:
print(user["name"]) # Ada, then GraceCount the levels. Print the value one step before the failing line, with type() and repr(). If it says <class 'str'>, you have already reached the bottom:
data = {"user": {"name": "Ada"}}
print(type(data["user"])) # <class 'dict'>
print(type(data["user"]["name"])) # <class 'str'>
print(repr(data["user"]["name"])) # 'Ada'Turn positions into whole numbers. Convert input() with int(), and divide with //, which always gives a whole number:
word = "python" middle = word[len(word) // 2] print(middle) # h position = int("2") # what int(input("Which letter? ")) gives for 2 print(word[position]) # t
When you'd see this in real code
- An API client that does
requests.get(url).textand then["data"]on the result. - A value stored with
json.dumpsin Redis, SQLite or a file, then read back withoutjson.loads. - A JSON field that holds JSON again, as a string inside the string. The outer
json.loadsworks and the inner value is still text, so calljson.loadsa second time on that field. - A loop over
configwhere you meantconfig["servers"], so each item is a key name, not a server dict.
Related errors
- TypeError: list indices must be integers or slices, not str: the same mistake on a list, usually a list of dicts you treated as one dict.
- AttributeError: 'str' object has no attribute 'X': the same unparsed JSON, found by
.get()instead of[ ]. - IndexError: string index out of range: the position is a whole number but past the end of the string.
- KeyError: you reached a real dict, but the key isn't in it.
- json.JSONDecodeError: Expecting value: when
json.loadsitself fails.
See Also
- All Python errors: the full index, by type and by when it happens.
- Working with Strings (tutorial)
- Dictionaries (tutorial)
- CSV and JSON
- Working with APIs
- JSON cheat sheet
Found this useful? Share it with a friend who’s learning Python.