πŸ”§ Error Fixes
Β· 2 min read
Last updated on

Python TypeError: String Indices Must Be Integers β€” How to Fix It


TypeError: string indices must be integers

What causes this

You’re treating a string like a dictionary. This usually happens when you expect a parsed JSON object (dict) but actually have a raw JSON string, or when you’re iterating over a data structure incorrectly and end up accessing individual characters of a string with a key instead of an index.

Fix 1: Parse your JSON first

The most common cause β€” you have a JSON string, not a dict:

# ❌ data is still a string
data = '{"name": "Alice", "age": 30}'
print(data['name'])  # TypeError!

# βœ… Parse it into a dict first
import json
data = json.loads('{"name": "Alice", "age": 30}')
print(data['name'])  # "Alice"

This also happens with API responses:

import requests

response = requests.get('https://api.example.com/user')

# ❌ response.text is a string
user = response.text
print(user['name'])  # TypeError!

# βœ… Use .json() to parse
user = response.json()
print(user['name'])  # Works

Fix 2: Check what you’re iterating over

When you loop over a dict, you get keys (strings). If you then try to index those strings with a key, you get this error:

data = {"users": [{"name": "Alice"}, {"name": "Bob"}]}

# ❌ Iterating over the dict gives you keys, not values
for item in data:
    print(item['name'])  # item is "users" (a string), not a dict!

# βœ… Iterate over the list inside the dict
for item in data['users']:
    print(item['name'])  # Works

Fix 3: Double-check nested structures

Sometimes the data structure isn’t what you expect:

# ❌ data[0] might be a string, not a dict
data = ["Alice", "Bob"]
print(data[0]['name'])  # TypeError!

# βœ… Check the type first
print(type(data[0]))  # <class 'str'>

Use type() or isinstance() to debug:

if isinstance(data, str):
    data = json.loads(data)
# Now safely access keys
print(data['name'])

Fix 4: File reading issues

Reading a JSON file but forgetting to parse it:

# ❌ read() returns a string
with open('data.json') as f:
    data = f.read()
    print(data['key'])  # TypeError!

# βœ… Use json.load() (not json.loads())
with open('data.json') as f:
    data = json.load(f)
    print(data['key'])  # Works

How to prevent it

  • Always use response.json() instead of response.text when working with APIs that return JSON
  • Use json.load() for files and json.loads() for strings β€” don’t mix them up
  • When debugging, print type(variable) before accessing keys to confirm you have a dict
  • Add type hints to your functions so your editor catches these mistakes early

Related: Pip Install Error Fix

πŸ“˜