Page 1 of 1

TypeError: string indices must be integers

Posted: Sat Jun 19, 2021 4:50 pm
by Xioto
So I have this bit of code that finds waveHeight and stores it as a cache, but when it reaches this section -

Code: Select all

sorted (data, key = lambda i: i['hours']) #sorts through cache_file data
print([0])
if 'waveHeight' in [0] and 'dwd' in [0]['waveHeight'] and[0]['waveHeight']['dwd'] >= 2.00: #if date and waveHeight found <2.00 then print
    print('Found')


It just gives me this error -

Code: Select all

    sorted (data, key = lambda i: i['hours']) #sorts through cache_file data
TypeError: string indices must be integers


I am in a bit of a hurry so if there is any more information you need then just ask, and I should respond soon!

Re: TypeError: string indices must be integers

Posted: Sat Jun 19, 2021 6:32 pm
by satoon101
The error indicates that data is not structured like you think it is. Print the value of data prior to the sorted line to verify it looks like you are intending it to.

*Edit: you might print type(data) as well to make sure the whole thing isn't a string.

Re: TypeError: string indices must be integers

Posted: Mon Dec 06, 2021 6:01 am
by markfilan
All the characters of a string have a unique index . This index specifies the position of each character of the string. TypeError: string indices must be integers means an attempt to access a location within a string using an index that is not an integer.

For example, str[hello"] and str[2.1] as indexes. As these are not integers, a TypeError exception is raised. This means that when you’re accessing an iterable object like a string or float value, you must do it using an integer value .

Python supports slice notation for any sequential data type like lists, strings , tuples, bytes, bytearrays, and ranges. When working with strings and slice notation, it can happen that a TypeError: string indices must be integers is raised, pointing out that the indices must be integers, even if they obviously are.