• 0 Vote(s) - 0 Average
• 1
• 2
• 3
• 4
• 5
[Tut] [FIXED] TypeError: string indices must be integers

[FIXED] TypeError: string indices must be integers

Problem Statement: Why am I seeing TypeError: string indices must be integers?

Reason: This error generally occurs when you use a string value to access an iterable object. In other words, it indicates that we are trying to access the value rom the index of an iterable using a string index instead of using an integer index. Thus, this means that the operation that we are trying to perform and the value upon which the operation is being performed are incompatible.

Let’s have a look at a scenario where we encounter this error, and then we will go ahead and find the solution to this problem.

## Example 1: Improper Value Extraction From a Dictionary

```di = { 'Website': 'Finxter', 'Language': 'Python', 'Creator': 'Chris'
}
for k in di: print(k['Website']) print(k['Language']) print(k['Creator'])```

Output:

``````Traceback (most recent call last): File "C:\Users\SHUBHAM SAYON\PycharmProjects\Finxter\TypeError.py", line 7, in print(k['Website'])
TypeError: string indices must be integers``````

Reason: In the above example, the `TypeError` occurred because we were trying to access the values of the dictionary using string indices instead of integers, as mentioned in the error message. The underlying reason has a bit more to it. If you have a look, you will find that we are trying to access the value of the dictionary using the key within the key with the help of the square bracket notation. That’s confusing the Python interpreter, and it throws an error accordingly.

### Solution

To avoid this error, you need to access the key of the dictionary directly from the dictionary itself. The value of `k` in the for loop of the above example itself represents the key of the dictionary. Thus, to access the key-value pair together, you can directly access the key from the loop and then use the key within the dictionary with the help of square bracket notation as sown below.

```di = { 'Website': 'Finxter', 'Language': 'Python', 'Creator': 'Chris'
}
for k in di: print(k, ":", di[k])```

Output:

``Website : Finxter Language : Python Creator : Chris``

Related Discussion: Python Dictionary Get Value – A Simple Illustrated Guide

## Example 2: Messing with String Indices

### Case 1: Usinga String to Access The a Character in The String

If you try to access a particular character within a given string using a string index, then – that leads to TypeError: string indices must be integers“. Let’s have a look at an example and try to extract the letter `'i'` from the given string and print it:

```text = "Welcome to Finxter"
print(text['i'])```

Output:

``Traceback (most recent call last): File "C:\Users\SHUBHAM SAYON\PycharmProjects\Finxter\TypeError.py", line 2, in <module> print(text['t']) TypeError: string indices must be integers``

Solution: The solution in this case is quite staright forward. You have to access the character using it’s index as shown below:

```text = "Welcome to Finxter"
print(text[12]) # i```

### Case 2: Improper Slicing

While slicing a string, if by any chance/mistake you try to slice the string using an incorrect syntax, then Python will throw `TypeError: string indices must be integers`. Let’s say that you try to slice the indices 0 to 7 as shown below:

```text = "Welcome to Finxter"
print(text[0, 7])```

Output:

``Traceback (most recent call last): File "C:\Users\SHUBHAM SAYON\PycharmProjects\Finxter\TypeError.py", line 2, in <module> print(text[0, 7]) TypeError: string indices must be integers``

Solution: The problem here is that we tried to slice the string using a comma. The proper syntax for slicing a string is `s[start:stop:step]`. Thus let’s use the proper syntax to solve the above problem.

```text = "Welcome to Finxter"
print(text[0:7]) # Welcome```

## Example 3: The Json Confusion

While working with `json` files it is quite common to encounter “TypeError: string indices must be integers“. Let’s have a look at the following example where we will get the error.

Consider that we have a a file named “voter.json” and and it has the following the contents:

```{"voters": [ { "name": "Shubham", "age": 28}, { "name": "Chris", "age": 32}, { "name": "Maricar", "age": 30}, { "name": "Max", "age": 1} ]
}```

From the above document let us try to compute the number of eligible voters and print the result.

```import json f = open('voter.json')
f.close() eligible = 0
for person in data: if person["age"] > 18: eligible += 1 print("Total Eligible Voters: ", eligible)```

Output:

``Traceback (most recent call last): File "C:\Users\SHUBHAM SAYON\PycharmProjects\Finxter\TypeError.py", line 9, in <module> if person["age"] > 18: TypeError: string indices must be``

Reason: In the above example `data` represents a dictionary while the variable `person` represents a key within the dictionary. This key has values attached to it and these values once again represent individual dictionaries. This means, just as we saw in the first example, we are trying to access a value using a key within another key and that’s leading to the occurrence of the error. The key is of the type string and not dict. Hence, the error appears. Let’s visualize this with the help of the following snippet:

It is evident from the above representation that person in the `for` loop represents the key ‘`voters`‘ of the dictionary data. Thus, person is of `string` type and it is not a dictionary itself.

Solution The solution is to access the value directly from the dictionary. You can do that by simply using accessing each value from the nested dictionary `voters` using the square bracket notation as follows:

```import json f = open('voter.json')
f.close()
eligible = 0
for person in data['voters']: if person["age"] > 18: eligible += 1
print("Eligible Voters: ", eligible)```

Output:

``Eligible Voters: 3``

Voila! That’s how you can work with json data in Python and avoid getting the TypeError.

## Conclusion

In this article, we discussed numerous scenarios describing the occurrence of “`TypeError: string indices must be integers"` and then we saw how to solve them. The rule of thumb to deal with this error is to ensure that whenever you try to access the value of an iterable, ensure that you do so by extracting the value from its index using an integer and not a string.

I hope this article helped you to solve your problem. Please stay tuned and subscribe for more interesting solutions and discussions. Happy learning!

To become a PyCharm master, check out our full course on the Finxter Computer Science Academy available for free for all Finxter Premium Members:

https://www.sickgaming.net/blog/2021/11/...-integers/

Forum Jump:

 Users browsing this thread: 1 Guest(s)

 Active Threads News - Video: We Have A Lot Of Feelings ... Last Post: xSicKxBot Yesterday 11:53 PM » Replies: 0 » Views: 15 News - Iconic Rockstar And Actor Meat Lo... Last Post: xSicKxBot Yesterday 11:53 PM » Replies: 0 » Views: 1 (Indie Deal) FREE Last Horizon, Microids... Last Post: xSicKxBot Yesterday 08:25 PM » Replies: 0 » Views: 10 Microsoft - Celebrating 20 years of Trus... Last Post: xSicKxBot Yesterday 08:25 PM » Replies: 0 » Views: 3 Xbox Wire - New EA Play Member Rewards F... Last Post: xSicKxBot Yesterday 08:25 PM » Replies: 0 » Views: 3 News - PS5 Will Outsell Series X|S 2:1 I... Last Post: xSicKxBot Yesterday 08:25 PM » Replies: 0 » Views: 4 [Tut] Pandas get_dummies() – A Simple Gu... Last Post: xSicKxBot Yesterday 04:18 PM » Replies: 0 » Views: 19 Mobile - Genshin Impact’s Tomo – vision,... Last Post: xSicKxBot Yesterday 04:18 PM » Replies: 0 » Views: 5 News - Community Focus: Parris Last Post: xSicKxBot Yesterday 04:18 PM » Replies: 0 » Views: 8 News - Bedrock: BETA 1.18.10.28 Last Post: xSicKxBot Yesterday 04:18 PM » Replies: 0 » Views: 8