python type_error ai_generated true

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

ID: python/typeerror-string-indices

Also available as: JSON · Markdown
95%Fix Rate
95%Confidence
50Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
311 active

Root Cause

Treating a string as a dict. Usually JSON wasn't parsed, or iterating dict gives keys not items.

generic

Workarounds

  1. 95% success If working with JSON, parse it first: data = json.loads(text)
    data = json.loads(text)

    Sources: https://docs.python.org/3/library/json.html#json.loads

  2. 90% success If iterating a dict, use .items() — for k in dict gives keys (strings), not dicts
    for item in data:  # item is a string key, not a dict!
    for key, value in data.items():  # correct

    Sources: https://docs.python.org/3/library/stdtypes.html#dict.items

Dead Ends

Common approaches that don't work:

  1. Convert string to dict with dict() 85% fail

    dict() can't parse JSON strings — use json.loads()

  2. Use int() on the index 80% fail

    The index is correct type — the object is wrong type

Error Chain

Frequently confused with: