String indices must be integers как исправить

В этой статье мы рассмотрим из-за чего возникает ошибка TypeError: String Indices Must be Integers и как ее исправить в Python.

На чтение 4 мин Просмотров 14.9к. Опубликовано 30.04.2021

В этой статье мы рассмотрим из-за чего возникает ошибка TypeError: String Indices Must be Integers и как ее исправить в Python.

Содержание

  1. Введение
  2. Что такое строковые индексы?
  3. Индексы строки должны быть целыми числами
  4. Примеры, демонстрирующие ошибку
  5. Использование индексов в виде строки
  6. Использование индексов в виде числа с плавающей запятой
  7. Решение для строковых индексов
  8. Заключение

Введение

В Python мы уже обсудили множество концепций и преобразований. В этом руководстве обсудим концепцию строковых индексов, которые должны быть всегда целыми числами. Как знаем в Python, доступ к итеративным объектам осуществляется с помощью числовых значений. Если мы попытаемся получить доступ к итерируемому объекту, используя строковое значение, будет возвращена ошибка. Эта ошибка будет выглядеть как TypeError: String Indices Must be Integers.

Что такое строковые индексы?

Строки — это упорядоченные последовательности символьных данных. Строковые индексы используются для доступа к отдельному символу из строки путем непосредственного использования числовых значений. Индекс строки начинается с 0, то есть первый символ строки имеет индекс 0 и так далее.

Индексы строки должны быть целыми числами

В python, когда мы видим какие-либо итерируемые объекты, они индексируются с помощью чисел. Если мы попытаемся получить доступ к итерируемому объекту с помощью строки, возвращается ошибка. Сообщение об ошибке — «TypeError: строковые индексы должны быть целыми числами».

Все символы, присутствующие в строках, имеют свой уникальный индекс. Индекс используется для указания позиции каждого символа в строке. Но все индексы должны быть целыми числами, поскольку мы не можем запомнить позицию с помощью символа, значения с плавающей запятой и так далее.

Примеры, демонстрирующие ошибку

Здесь мы обсудим все примеры, которые покажут вам ошибку в вашей программе, поскольку строковые индексы должны быть целыми числами:

Использование индексов в виде строки

В этом примере будем использовать строку в переменной line. Затем мы попытаемся получить доступ к конкретному индексу строки с помощью строкового символа в качестве индекса, а затем посмотрим результат. 

Давайте посмотрим на пример для детального понимания концепции.

line = "Тестовая строка"

string = line["е"]
print(string)

Вывод программы:

Traceback (most recent call last):
  File "D:ProjectTESTp.py", line 3, in <module>
    string = line["е"]
TypeError: string indices must be integers

Объяснение:

  • Мы использовали входную строку в переменной line
  • Затем мы взяли переменную string, в которую мы передали значение индекса в виде строкового символа.
  • Наконец, мы распечатали результат.
  • Следовательно, вы можете увидеть ошибку TypeError: String Indices Must be Integers, что означает, что вы не можете получить доступ к строковому индексу с помощью символа.

Использование индексов в виде числа с плавающей запятой

В этом примере мы возьмем входную строку. А затем попробуйте получить доступ к строке с помощью значения с плавающей запятой в качестве их индекса. Затем мы увидим результат. 

Давайте посмотрим на пример для детального понимания концепции.

line = "Тестовая строка"

string = line[1.6]
print(string)

Вывод программы:

Traceback (most recent call last):
  File "D:ProjectTESTp.py", line 3, in <module>
    string = line[1.6]
TypeError: string indices must be integers

Объяснение:

  • Во-первых, мы взяли входную строку.
  • Затем мы взяли переменную string, в которую мы передали значение индекса как число с плавающей запятой в диапазоне строки.
  • Наконец, мы распечатали результат.
  • Следовательно, вы можете увидеть «TypeError: строковые индексы должны быть целыми числами», что означает, что вы не можете получить доступ к строковому индексу с помощью числа с плавающей запятой

Решение для строковых индексов

Единственное решение для этого типа ошибки: «Строковые индексы должны быть целыми числами» — это передать значение индекса как целочисленное значение. Поскольку доступ к итерируемому объекту можно получить только с помощью целочисленного значения. Давайте посмотрим на пример для детального понимания концепции.

line = "Тестовая строка"

string = line[3]
print(string)

Вывод программы:

Объяснение:

  • Во-первых, мы взяли входную строку.
  • Затем мы взяли переменную, в которую мы передали значение индекса как целое число в диапазоне строки.
  • Наконец, мы распечатали результат.
  • Следовательно, вы можете увидеть вывод буквы «т», поскольку 3-й символ строки — «т».

Заключение

В этом руководстве мы узнали о концепции «TypeError: строковые индексы должны быть целыми числами». Мы видели, что такое строковые индексы? Также мы увидели, почему строковые индексы должны быть целыми числами. Мы объяснили этот тип ошибки с помощью всех примеров и дали код решения для ошибки. Все ошибки подробно объясняются с помощью примеров. Вы можете использовать любую из функций по вашему выбору и вашим требованиям в программе.

Однако, если у вас есть какие-либо сомнения или вопросы, дайте мне знать в разделе комментариев ниже. Я постараюсь помочь вам как можно скорее.

Ситуация: мы пишем программу, которая будет работать как словарь. Нам нужно отсортировать по алфавиту не слова, а словосочетания. Например, если у нас есть термины «Большой Каньон (США)» и «Большой Взрыв (Вселенная)». Первые слова одинаковые, значит, порядок будет зависеть от вторых слов. Получается, что сначала должен идти «Большой Взрыв», а потом «Большой Каньон», потому что «В» идёт в алфавите раньше, чем «К». 

Для этого мы пишем функцию, которая возвращает нам номер символа, стоящего сразу после пробела — whatNext(), а потом используем её, чтобы получить букву из строки:

def whatNext():
  # какой-то код, где переменная ind отвечает за номер символа
  return ind

# дальше идёт код нашей основной программы
# доходим до момента, когда нужно получить символ из строки phrase
# вызываем функцию и сохраняем то, что она вернула, в отдельную переменную
symbolIndex = whatNext()
# используем эту переменную, чтобы получить доступ к символу
symbol = phrase[symbolIndex]

Но после запуска компьютер выдаёт ошибку:

❌ TypeError: string indices must be integers

Что это значит: интерпретатор говорит нам, что обращаться к содержимому строку через индекс (порядковый номер символа в строке) можно только с помощью целых чисел. 

Когда встречается: когда вместо целого числа интерпретатор видит не его, а что-то другое — символ, другую строку, дробное число, объект или что-то ещё. Это единственная причина, по которой возникает такая ошибка.

Что делать с ошибкой TypeError: string indices must be integers

Раз мы знаем единственную причину, то решение очевидное: нужно проверить, что именно мы отправляем в качестве индекса. Судя по всему, проблема в нашей функции whatNext(), которая возвращает не целое число, а что-то иное. Сейчас мы не знаем, что именно, потому что мы не знаем, как работает whatNext().

Можно предположить, что в функции whatNext() происходили какие-то вычисления, которые возвращали не целое, а дробное число. При этом само число могло быть целым (например, 12), просто его зачем-то приводили к десятичной дроби (12,00). 

Другой вариант — функция возвращала не число, а строку с числом внутри, кортеж с одним числом, объект с числом. Для нас, людей, это всё ещё целое число, но для Python это другой тип данных. 

Чтобы это исправить, нужно зайти внутрь функции и перепроверить, что она возвращает.

Вот пара примеров, которые могут возникнуть во время работы:

Что означает ошибка TypeError: string indices must be integers

Что означает ошибка TypeError: string indices must be integers

Что означает ошибка TypeError: string indices must be integers

Но если поставить в индекс целое число — всё сработает, и мы получим символ, который стоит на этом месте в строке. На всякий случай напомним, что нумерация символов в Python идёт с нуля:

Что означает ошибка TypeError: string indices must be integers

Вёрстка:

Кирилл Климентьев

Introduction

In python, we have discussed many concepts and conversions. In this tutorial, we will be discussing the concept of string indices must be integers. As we all know in python, iterable objects are accessed with the help of numeric values. If we try to access the iterable object using a string value, an error will be returned. This error will look like “TypeError: string indices must be integers.”

What are string indices?

Strings are the ordered sequences of character data. String indices are used to access the individual character from the string by directly using the numeric values. The string index starts with 0, i.e., the first character of the string is at 0 indexes and so on.

In python, when we see any iterable objects, these are indexed using numbers. If we try to access the iterable object with the help of a string, an error is returned. Error shows – “TypeError: string indices must be integers.”

All the characters which are present in the strings have their unique index. The index is used to specify the position of each character of the string. But all the indexes must be integers as we cannot remember the position with the help of a character, float value, etc.

Before moving further, I want to let you know that If you are coding in Python for a while, you might get many typeerrors every other day. To solve these errors, you can read our in-depth guide of the following typeerrors:

  • How to Solve TypeError: ‘int’ object is not Subscriptable
  • Invalid literal for int() with base 10 | Error and Resolution
  • [Solved] TypeError: Only Size-1 Arrays Can Be Converted To Python Scalars Error
  • How to solve Type error: a byte-like object is required not ‘str’

Examples showing the error String indices must be integer

Here, we will be discussing all the examples which will show you the error in your program as String indices must be an integer:

1. Taking indices as string

In this example, we will be taking an input string as str. Then, we will try to access the particular index of the string with the help of the string as the index. And then, see the output. Let us look at the example for understanding the concept in detail.

#input string
str = "Pythonpool"

p = str["p"]
print(p)

Output:

Taking indices as string

Explanation:

  • Firstly, we have taken an input string as str.
  • str = “Pythonpool”.
  • Then, we have taken a variable p in which we have passed the index value as a character in the range of the string.
  • The range of index of string starts from 0 and ends at the length of string- 1.
  • At last, we have printed the output.
  • Hence, you can see the “TypeError: string indices must be integers” which means you cannot access the string index with the help of character.

2. Taking indices as a float value

In this example, we will take an input string as str. And then, try to access the string with the help of float value as their index. Then, we will see the output. Let us look at the example for understanding the concept in detail.

#input string
str = "Pythonpool"

p = str[1.2]
print(p)

Output:

Taking indices as a float value

Explanation:

  • Firstly, we have taken an input string as str.
  • str = “Pythonpool”.
  • Then, we have taken a variable p in which we have passed the index value as the float in the range of the string.
  • The range of index of string starts from 0 and ends at the length of string- 1.
  • At last, we have printed the output.
  • Hence, you can see the “TypeError: string indices must be integers,” which means you cannot access the string index with the help of character.

3. string indices must be integers while parsing JSON using Python

In this example, we will see that while we are parsing on JSON, string indices must be integers. Let us look at the example for understanding the concept in detail.

import json
input_string = '{"coord": {"lon": 4.49, "lat": 50.73}, "weather": [{"id": 800, "main": "Clear", "description": "clear sky", "icon": "01d"}], "base": "stations", "main": {"temp": 26.96, "feels_like": 23.13, "temp_min": 26.11, "temp_max": 27.78, "pressure": 1016, "humidity": 26}, "visibility": 10000, "clouds": {"all": 0}, "dt": 1596629272, "timezone": 7200, "id": 2793548, "name": "La Hulpe", "cod": 200}'
data = json.loads(input_string)
for i in data['weather']:
    print(i['main'])
for j in data['main']:
    print(j['temp'])

Output:

string indices must be integers while parsing JSON using Python

Solution for String indices must be integers Error

The only solution for this type of error: “String indices must be integers” is to pass the index value as the integer value. As the iterable object can only be accessed with the help of the integer value. Let us look at the example for understanding the concept in detail.

#input string
str = "Pythonpool"

p = str[5]
print("output : ",p)

Output:

Solution for String indices must be integers Error

Explanation:

  • Firstly, we have taken an input string as str.
  • Str = Pythonpool.
  • Then, we have taken a variable p in which we have passed the index value as an integer in the range of the string.
  • The range of index of string starts from 0 and ends at the length of string- 1.
  • At last, we have printed the output.
  • Hence, you can see the output as ‘n’ as the 5th character of the string is ‘n.’

Conclusion

In this tutorial, we have learned about the concept of “TypeError: string indices must be integers.” We have seen what string indices are? Also, we have seen why string indices should be integers. We have explained this type of error with the help of all the examples and given the solution code for the error. All the examples are explained in detail with the help of examples. You can use any of the functions according to your choice and your requirement in the program.

However, if you have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.

Typeerror: string indices must be integers – How to Fix in Python

In Python, there are certain iterable objects – lists, tuples, and strings – whose items or characters can be accessed using their index numbers.

For example, to access the first character in a string, you’d do something like this:

greet = "Hello World!"

print(greet[0])
# H

To access the value of the first character in the greet string above, we used its index number: greet[0].

But there are cases where you’ll get an error that says, «TypeError: string indices must be integers» when trying to access a character in a string.

In this article, you’ll see why this error occurs and how to fix it.

There are two common reasons why the «TypeError: string indices must be integers» error might be raised.

We’ll talk about these reasons and their solutions in two different sub-sections.

How to Fix the TypeError: string indices must be integers Error in Strings in Python

As we saw in last section, to access a character in a string, you use the character’s index.

We get the «TypeError: string indices must be integers» error when we try to access a character using its string value rather the index number.

Here’s an example to help you understand:

greet = "Hello World!"

print(greet["H"])
# TypeError: string indices must be integers

As you can see in the code above, we got an error saying TypeError: string indices must be integers.

This happened because we tried to access H using its value («H») instead of its index number.

That is, greet["H"] instead of greet[0]. That’s exactly how to fix it.

The solution to this is pretty simple:

  • Never use strings to access items/characters when working with iterable objects that require you to use index numbers (integers) when accessing items/characters.

How to Fix the TypeError: string indices must be integers Error When Slicing a String in Python

When you slice a string in Python, a range of characters from the string is returned based on given parameters (start and end parameters).

Here’s an example:

greet = "Hello World!"

print(greet[0:6])
# Hello 

In the code above, we provided two parameters – 0 and 6. This returns all the characters within index 0 and index 6.

We get the «TypeError: string indices must be integers» error when we use the slice syntax incorrectly.

Here’s an example to demonstrate that:

greet = "Hello World!"

print(greet[0,6])
# TypeError: string indices must be integers

The error in the code is very easy to miss because we used integers – but we still get an error. In cases like this, the error message may appear misleading.

We’re getting this error because we used the wrong syntax. In our example, we used a comma when separating the start and end parameters: [0,6]. This is why we got an error.

To fix this, you can change the comma to a colon.

When slicing strings in Python, you’re required to separate the start and end parameters using a colon – [0:6].

Summary

In this article, we talked about the «TypeError: string indices must be integers» error in Python.

This error happens when working with Python strings for two main reasons – using a string instead of an index number (integer) when accessing a character in a string, and using the wrong syntax when slicing strings in Python.

We saw examples that raised this error in two sub-sections and learned how to fix them.

Happy coding!



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

String indices must be integers. This means that when obtaining an iterable object like a string, you must do it using a numerical value.

What are string indices?

String indices allow you to directly access individual characters in a string using a numeric value.

String indexing is zero-based, which means the first character in the string has an index of 0, the next character has 1, and so on.

String indexing in Python

To access a character of a string, reference it by its index numbers using the square brackets([ ]).

data = "EnolaHolmes2"
print(data[5])

Output

H

We accessed the character “H” from a string “EnolaHolmes2” using string indexing.

What is TypeError in Python?

TypeError in Python is an exception when the data type of an object in operation is inappropriate.

Why does TypeError occur?

The TypeError occurs because an operation is performed on an object of an incorrect type or is not supported.

After reviewing my entire codebase, I discovered the following reason that caused the error.

Typeerror: string indices must be integers error in Python occurs when we are attempting to access a value from an iterable using a string index rather than an integer index.

The iterable objects are indexed using numbers. Therefore, an error will be returned when you try to obtain an iterable object using a string value.

See the following example of code.

main_string = "metaverse"
index = "1"

print(main_string[index])

If you run the above code, you will get the TypeError.

TypeError: string indices must be integers

How to fix TypeError: String indices must be integers

Following is the answer that I came up with after carefully reviewing my codebase and performing a lot of trial-and-error approaches with the code.

To fix TypeError: string indices must be integers error, ensure you use an integer as the index when accessing a character in a string.

The built-in int() function converts a non-integer index to an integer.

main_string = "metaverse"
index = "1"

print(main_string[int(index)])

Output

e

See, it returns the second element of the string whose index is 1st because the index starts from 0 in Python.

We successfully solved TypeError: string indices must be integers error by converting an index to an integer using the int() function.

However, this approach is imperfect and will only work if the index can be successfully converted to an integer.

If the index is not a valid integer, it will raise a ValueError instead.

For example, if the index is “x” instead of “1” in the above code, it will raise a ValueError.

main_string = "metaverse"
index = "x"

print(main_string[int(index)])

Output

ValueError: invalid literal for int() with base 10: 'x'

Use the int() function approach when the index is convertible to int.

Tips and best practices for avoiding the “TypeError: String Indices must be Integers” error in the future

  1. Use integer indices when accessing elements of a string.
  2. Use the isinstance() function to check the variable type before using it as a string index.
  3. While iterating a for loop, use the loop variable as an integer index.
  4. If you are working with string indices stored as strings, convert them to integers using the int() function before using them as indices.

FAQs

What common mistakes can cause the “TypeError: String Indices must be Integers” error?

  1. Using a variable that is not an integer as a string index.
  2. Confusing string indices with string methods.
  3. Use a for loop variable that is not an integer as a string index.
  4. Using string indices stored as strings without converting them to integers first.

How can I avoid the “TypeError: String Indices must be Integers” error in the future?

  1. Use integer indices when accessing elements of a string.
  2. Use the isinstance() function that checks the variable type before using it as a string index.
  3. When storing string indices as strings, convert them to integers before using them as indices.

Conclusion

The string indices must be integer error occurs when accessing a string element using an invalid data type index instead of an int type index.

Ensure you use an integer as the index when accessing a character in a string to fix the TypeError.

Further reading

TypeError: ‘int’ object is not subscriptable

TypeError: bad operand type for unary +: ‘str’

TypeError: can only concatenate str not int to str

Добрый день!

Подскажите, пожалуйста, что делаю не так, вот в этом коде, мне нужно, передать данные в json формате:

import json
import sys


def handle(data):
    data = json.loads(data)
    arr1 = data['items']
    arr2 = data['rates']
    arr3 = ''
    companiesDict = { n['id']: { k: n[k] for k in ('name', 'disabled') } for n in arr1 }
    arr3 = [{ **n, **companiesDict.get(n['company'], {}) } for n in arr2 ]
    return arr3

items

[{‘id’: 14, ‘alias’: ‘maks’, ‘name’: ‘Макс’, ‘disabled’: False}, {‘id’: 4, ‘alias’: ‘rgs’, ‘name’: ‘Росгосcтрах’, ‘disabled’: False}, {‘id’: 12, ‘alias’: ‘vsk’, ‘name’: ‘ВСК’, ‘disabled’: False}, {‘id’: 9, ‘alias’: ‘soglasie’, ‘name’: ‘Согласие’, ‘disabled’: False}, {‘id’: 3, ‘alias’: ‘renins’, ‘name’: ‘Ренессанс’, ‘disabled’: False}, {‘id’: 2, ‘alias’: ‘ingos’, ‘name’: ‘Ингосстрах’, ‘disabled’: False}, {‘id’: 7, ‘alias’: ‘tinkoff’, ‘name’: ‘Тинькофф’, ‘disabled’: False}, {‘id’: 13, ‘alias’: ‘mafin’, ‘name’: ‘Mafin’, ‘disabled’: False}, {‘id’: 8, ‘alias’: ‘ugsk’, ‘name’: ‘Югория’, ‘disabled’: False}, {‘id’: 1, ‘alias’: ‘zetta’, ‘name’: ‘Зетта’, ‘disabled’: False}, {‘id’: 0, ‘alias’: ‘alfa’, ‘name’: ‘Альфа’, ‘disabled’: False, ‘retentionType’: 1}, {‘id’: 17, ‘alias’: ‘osk’, ‘name’: ‘ОСК’, ‘disabled’: False}, {‘id’: 15, ‘alias’: ‘absolute’, ‘name’: ‘Абсолют Страхование’, ‘disabled’: False}, {‘id’: 16, ‘alias’: ‘euroins’, ‘name’: ‘ЕВРОИНС’, ‘disabled’: False}, {‘id’: 5, ‘alias’: ‘sds’, ‘name’: ‘СДС’, ‘disabled’: True}, {‘id’: 18, ‘alias’: ‘guidehins’, ‘name’: ‘Гайде’, ‘disabled’: False}, {‘id’: 19, ‘alias’: ‘astrovolga’, ‘name’: ‘Астро-Волга’, ‘disabled’: False}, {‘id’: 11, ‘alias’: ‘reso’, ‘name’: ‘РЕСО’, ‘disabled’: True, ‘retentionType’: 1}, {‘id’: 6, ‘alias’: ‘sngi’, ‘name’: ‘Сургутнефтегаз’, ‘disabled’: True}, {‘id’: 10, ‘alias’: ‘svrezv’, ‘name’: ‘Сервис резерв’, ‘disabled’: True}]

rates

[{‘company’: 0, ‘base’: 4390, ‘price’: 3817.32}, {‘company’: 1, ‘base’: 4118, ‘price’: 3580.81}, {‘company’: 2, ‘base’: 4560, ‘price’: 3965.15}, {‘company’: 3, ‘base’: 4430, ‘price’: 3852.11}, {‘company’: 4, ‘base’: 4550, ‘price’: 3956.45}, {‘company’: 5, ‘base’: 4000, ‘price’: 3478.2}, {‘company’: 6, ‘base’: 4000, ‘price’: 3478.2}, {‘company’: 7, ‘base’: 4250, ‘price’: 3695.59}, {‘company’: 8, ‘base’: 4000, ‘price’: 3478.2}, {‘company’: 9, ‘base’: 4430, ‘price’: 3852.11}, {‘company’: 10, ‘base’: 4000, ‘price’: 3478.2}, {‘company’: 11, ‘base’: 4118, ‘price’: 3580.81}, {‘company’: 12, ‘base’: 4250, ‘price’: 3695.59}, {‘company’: 13, ‘base’: 4000, ‘price’: 3478.2}, {‘company’: 14, ‘base’: 4000, ‘price’: 3478.2}, {‘company’: 15, ‘base’: 4000, ‘price’: 3478.2}, {‘company’: 16, ‘base’: 4000, ‘price’: 3478.2}, {‘company’: 17, ‘base’: 4000, ‘price’: 3478.2}, {‘company’: 18, ‘base’: 4000, ‘price’: 3478.2}, {‘company’: 19, ‘base’: 4000, ‘price’: 3478.2}]

постоянно вылезает ошибка: TypeError: string indices must be integers

Дополнение: Полное описание ошибки

exit status 1
Traceback (most recent call last):
File «index.py», line 19, in
ret = handler.handle(st)
File «/home/app/function/handler.py», line 30, in handle
exec(code,glob,ldict)
File «», line 14, in
File «», line 10, in handle
File «», line 10, in
File «», line 10, in
TypeError: string indices must be integers

Posted by Marta on May 2, 2021 Viewed 13940 times

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:

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:

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

youtube comment bot
how to make a website like youtube
rock paper scissors java

Понравилась статья? Поделить с друзьями:
  • Stop code whea uncorrectable error
  • Stop code acpi bios error
  • Stop chassis error ошибка на туарег зимой
  • Stop car too low w211 как убрать ошибку
  • Stop c00021a fatal system error что делать