Why am I seeing TypeError string indices must be integers?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
TypeError: string indices must be integers means you are using a string key (like ["name"]) to index into a value that is a str, not a dict. Python strings can only be indexed with integers (e.g., s[0], s[1:3]). The error almost always happens because a variable you expect to be a dictionary or a parsed JSON object is actually still a raw JSON string, or because you are iterating over a data structure and getting individual items where you expected nested objects.
The Most Common Cause: Unparsed JSON
This happens frequently with HTTP responses:
Iterating Over a Dict Gets Keys, Not Items
Iterating Over a List of Dicts
Nested JSON Gotcha
Some APIs return nested JSON as an escaped string within the outer JSON. Always check the type before indexing.
Debugging Strategy
When you hit this error, the first step is to check what type your variable actually is:
String Indexing Review
Strings support only integer indices and slices:
Common Scenarios That Trigger This Error
| Scenario | What You Have | What You Expected | Fix |
| API response not parsed | str | dict | Call .json() or json.loads() |
| Iterating over dict | Key str | Dict item | Use .items() or index the dict directly |
| Nested JSON string | str field in dict | Nested dict | json.loads() the inner string |
| CSV field | str value | dict | Parse with csv.DictReader or split |
| YAML not parsed | str | dict | yaml.safe_load() the string |
Common Pitfalls
- Forgetting to parse API responses:
requests.get().textis a string. Use.json()to get a dictionary. If the API returns non-JSON, checkContent-Typeheaders. - Double-encoded JSON: Some APIs return JSON where string values contain escaped JSON. You need to call
json.loads()twice — once for the outer string, once for the inner. - Iterating over a dict vs a list of dicts:
for x in my_dictgives you keys (strings).for x in my_list_of_dictsgives you dicts. Check your data shape. - YAML or config files read as strings:
open("config.yaml").read()gives you a string. Useyaml.safe_load(open("config.yaml"))to get a dictionary. - Pandas DataFrame confusion:
df["column"]works on DataFrames, but if you accidentally have a string instead of a DataFrame, you get this error. Verify withtype(df).
Summary
- This error means you are indexing a string with a non-integer key like
["name"] - The most common cause is treating an unparsed JSON string as a dictionary
- Fix by parsing the string first:
json.loads(string)orresponse.json() - Always check
type(variable)andrepr(variable)when debugging - When iterating over a dict, you get keys (strings), not values — use
.items()for key-value pairs - Use
isinstance(value, str)to guard against type confusion before indexing

