Python throws typeerror string indices must be integers when you try to index strings using another string. For example –

>>> superhero = 'Captain America'
>>> print(superhero[1])
a
>>> print(superhero["2"])
Error: string indices must be integers

In this code, we are defining a string variable superhero which is indexed as superhero[1] and superhero["2"]. superhero[1] is correct but superhero["2"] will raise “string indices must be integers” error.

We use string indices in case of dictionaries and json data. If you have defined a dictionary or json and still getting this error, then it means due to some part in the code you are either reassigning the variable as string or some library doing that.

This code example will show you a real project error. Here we will try to print a json but Python will throw error. Suppose, we have a json file superhero.json

{
    "avengers": [
                    {"name": "Captain America", "weapon": "Shield"}, 
                    {"name": "Ironman", "weapon": "Suit"},
                    {"name": "Hulk", "weapon": "Anger"},
                    {"name": "Thor", "weapon": "Thunder"},
                    {"name": "Black Widow", "weapon": "Agility"},
                    {"name": "Doctor Strange", "weapon": "Magic"}
                ]
}

And we are opening this Json file into our python code –

import json

f=open('superhero.json')
data = json.load(f)
f.close()

for item in data:
    print([item["name"], item["weapon"]])

The code will raise error in print([item["name"], item["weapon"]]) line saying that item is a string and we are using strings to index it.

Traceback (most recent call last):
  File "Main.py", line 8, in <module>
    print([item["name"], item["weapon"]])
TypeError: string indices must be integers

So, where did we do wrong? If you print item, you will see that its value is avengers. We want it to be the dictionary of separate superheroes but got string. The problem is that data variable holds the whole superhero.json. And, the array of superheroes is in the property avengers. The for loop for item in data will run on the whole json and not on avengers property. That’s why item holds avengers value.

To correct this code, we need to make a small change in our for loop –

for item in data["avengers"]:

    Tweet this to help others

Live Demo

Demo might not work in private window (incognito)

Comments

About the Author

akamit

I am Akash Mittal, an overall computer scientist. If you want to guest post, need help in your projects, want to advertise, Feel free to contact me at [email protected]

View All Articles