PythonMastery
reference 3 min read · lesson 5 of 80 in Errors

TypeError: string indices must be integers, not 'str'

1 · The lesson

read

What 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

python
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:

python
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.

python
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.

python
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.

python
data = {"user": {"name": "Ada"}}
name = data["user"]["name"]     # "Ada"
print(name["first"])            # TypeError: "Ada" is a string

4. 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:

python
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:

python
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 admin

If you actually have a list of dicts, loop over the list. Each item is then a dict:

python
users = [{"name": "Ada"}, {"name": "Grace"}]
for user in users:
    print(user["name"])    # Ada, then Grace

Count 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:

python
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:

python
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).text and then ["data"] on the result.
  • A value stored with json.dumps in Redis, SQLite or a file, then read back without json.loads.
  • A JSON field that holds JSON again, as a string inside the string. The outer json.loads works and the inner value is still text, so call json.loads a second time on that field.
  • A loop over config where you meant config["servers"], so each item is a key name, not a server dict.

See Also

Found this useful? Share it with a friend who’s learning Python.