How To Fix String Indices must be Integers in Python

Posted by Marta on May 2, 2021 Viewed 2722 times

Learn how to fix the TypeError: string indices must be integers error in Python with examples. More robust programming style.

Card image cap

In this article, I will explain the main reason why you will face the TypeError: string indices must be integers error in Python along with a few different examples. I think it is essential to understand why this error occurs, since the better you understand the error, the better your ability to avoid it.

This tutorial contains some code examples and possible ways to fix the error.

String Indices must be Integers

A String in Python is a sequence of characters. Each of this character can be accessed using its index position. Using anything else but an integer to index a string will raise a String Indices must be Integers error . For example:

variable1 = "Hello Code Club"

print(variable1[0]) #Correct

print(variable1['Hello'] # ERROR

Output:

H

Traceback (most recent call last):
  File  line 5, in <module>
    print(variable1['Hello'])  # Error
TypeError: string indices must be integers

Check out line 5. A String should be indexed using an integer, but instead, the code in line 5 is indexing using not an integer but a string. Python doesn’t know how to execute this statement, and therefore it throws an error because it can continue with the execution.

In most cases you will face this problem because you assume that a given variable is a dictionary, but it is a String.

This error is very common because Python is not a strongly type language, in other words, variables don’t have a fixed type associated to them.

Dictionary Example

This error looks straightforward; however, when we are working with dictionaries, it might not be as obvious. Let’s see a code snippet that will raise our error:

variable1 = {
    'name': "Luke",
    'age': 347
}

for item in variable1:
    print(item['name'])

Output:

Traceback (most recent call last):
  File line 7, in <module>
    print(item['name'])
TypeError: string indices must be integers

This code snippet aims to print out all values inside the dictionary. Why is it raising an error? The item variable in line 7 is a String, not a dictionary.

To understand this, it is essential to point out when using a dictionary in a for loop, by default, the code will loop over the dictionary keys, not over the values. See the example below:

variable1 = {
    'name': "Luke",
    'age': 347
}
for item in variable1:
    print(item)

Output:

name
age

To loop over the values, we need to called the method .values():

variable1 = { 'name': "Luke", 'age': 347}

for item in variable1.values():
    print(item)

Output:

Luke
347

Working with Json Example

Another example where the “TypeError: string indices must be integers” error occur is when working with JSON. Let’s imagine that we have a file containing employees information, all saved in JSON format in a file. And we want to write a piece of code that returns the numbers of employees over 30. See below the code snippet:

employees.json

{"employees":
  [
    { "name": "Luke", "age": 21},
    { "name": "Marta", "age": 32},
    { "name": "Mike", "age": 45},
    { "name": "Jane", "age": 22}
  ]
}
import json

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

employee_above_30s = 0
for employee in data:
    if employee["age"]>30:
        employee_above_30s+=1

print(employee_above_30s)

After running the above code, we get an error. Why? The problem is in line 9. We are assuming the employee variable is a dictionary but it’s actually a string that contains the value “employees”, which is .

Therefore the solution is avoiding trying to access a field on a String, and use the dictionary instead. The easiest way to fix the above code snippet is replacing line 8 by for employee in data['employees'], as below:

employee_above_30s = 0
for employee in data['employees']:
    if employee["age"]>30:
        employee_above_30s+=1

The employee is now a dictionary instead of a String.

Knowledge Quiz

Here is a chance to check how much you learned. See below a few quiz questions that will help you to confirm and reinforce your understanding. Find the solutions at the bottom of this article:

  1. What would this program output?
variable = "Hello"
print(variable["1"])

A) H

B) e

C) string indices must be integers error

Conclusion

To summarise, we have seen a few scenarios where you could face the “TypeError: string indices must be integers” error and how you can fix it by making sure you only use string indices on dictionaries.

I hope you enjoy this article, and understand this issue better to avoid it when you are programming.

Thank you so much for reading and supporting this blog!

Happy Coding!

Solution

1.C

More Interesting Articles

Project-Based Programming Introduction

Steady pace book with lots of worked examples. Starting with the basics, and moving to projects, data visualisation, and web applications

100% Recommended book for Java Beginners

Unique lay-out and teaching programming style helping new concepts stick in your memory

90 Specific Ways to Write Better Python

Great guide for those who want to improve their skills when writing python code. Easy to understand. Many practical examples

Grow Your Java skills as a developer

Perfect Boook for anyone who has an alright knowledge of Java and wants to take it to the next level.

Write Code as a Professional Developer

Excellent read for anyone who already know how to program and want to learn Best Practices

Every Developer should read this

Perfect book for anyone transitioning into the mid/mid-senior developer level

Great preparation for interviews

Great book and probably the best way to practice for interview. Some really good information on how to perform an interview. Code Example in Java