@MZeeshanM to PythonEnglish • 6 days ago

Why does Python raise "TypeError: string indices must be integers" and how do you resolve it?

message-square
0
1
Why does Python raise "TypeError: string indices must be integers" and how do you resolve it?
@MZeeshanM to PythonEnglish • 6 days ago

Python raises TypeError: string indices must be integers when you attempt to index or key into a str object using a string key (like data["name"]) instead of an integer index or slice (like data[0] or data[0:4])—most commonly because a JSON payload, API response, or CSV row was loaded as a raw unparsed str rather than a parsed dict. Resolve it by parsing the JSON string into a dictionary with json.loads() (or response.json()) before accessing string keys, or by indexing the string with integer positions.

Basic Example

import json

raw_payload = '{"user": "Alice", "role": "admin"}'

# WRONG: 'raw_payload' is still a str, so indexing with key "user" raises TypeError
# print(raw_payload["user"])
# -> TypeError: string indices must be integers, not 'str'

# 1. FIX A: Parse the JSON string into a Python dict first using json.loads()
parsed_data = json.loads(raw_payload)
print(parsed_data["user"])  # Output: "Alice"

# 2. FIX B: If you intentionally want characters from a string, use integer indices or slices
word = "Python"
print(word[0])     # Output: "P"
print(word[0:3])   # Output: "Pyt"

Key Details & Common Scenarios

  • 1. Unparsed or double-encoded JSON from APIs / files (json.loads()):
    • Accessing response.text["id"] on a requests HTTP response fails because .text is a str; call response.json()["id"] instead.
    • Double-encoded JSON: Sometimes an API or database returns JSON wrapped inside a JSON string ('"{\\"id\\": 42}"'). Calling json.loads() once returns a str, so data["id"] still raises TypeError: string indices must be integers. Check isinstance(data, str) and call json.loads(data) a second time if needed.
  • 2. Iterating directly over a dictionary instead of .values() or .items(): Looping for item in my_dict: yields the dictionary’s keys (which are usually str objects), not the nested sub-dictionaries:
    users = {
        "u1": {"name": "Alice", "age": 30},
        "u2": {"name": "Bob", "age": 25},
    }
    
    # WRONG: 'u' is the key string ("u1"), not the inner dict
    # for u in users:
    #     print(u["name"])  # TypeError: string indices must be integers
    
    # FIX: Iterate over .values() or .items()
    for user_info in users.values():
        print(user_info["name"])
    
  • 3. Iterating over a string instead of a list of dictionaries: If a variable expected to be a list[dict] (such as [{"id": 1}, {"id": 2}]) accidentally holds a single str (like "error"), looping for row in records: print(row["id"]) assigns single characters ("e", "r", …) to row and crashes on row["id"]. Inspect type(records) before looping.
  • 4. Reading CSV files with csv.reader instead of csv.DictReader: csv.reader yields each row as a list[str] (or a single str if iterated over a line), requiring integer indices (row[0]). Use csv.DictReader(file) if you want to access columns by header name (row["email"]).

Common Causes & Targeted Fixes Reference

Scenario / Broken Code Why obj Is a str Resolution
raw = '{"a": 1}'; raw["a"] Raw JSON text was never deserialized into a dict Parse first: data = json.loads(raw); data["a"]
resp = requests.get(url); resp.text["a"] .text returns the HTTP body as a str Use resp.json()["a"]
for k in my_dict: k["subkey"] Iterating a dict yields its string keys, not its values Iterate for v in my_dict.values(): v["subkey"]
data = json.loads(double_json); data["a"] JSON string was serialized twice ("\"{\\\"a\\\": 1}\"") Decode again if isinstance(data, str): data = json.loads(data)
for row in csv.reader(f): row["col"] csv.reader yields positional lists, not key-value mappings Switch to csv.DictReader(f) or index by integer row[0]