I'm reading a Dictionary from an API which has a field called 'price'.
I'm reading it fine for a while (so, the code works) until I get to a point I get the error message: string indices must be integers.
That breaks my code.
So, I would like to find a way to skip it (ignore it) when this happens, and continue with the code. And just print something out so I know something happened.
So, far I don't manage to see what number is causing this error.
If I test this by itself, it works fine.
fill = {'price': 0.00002781 }
price = fill['price'] # OUTPUT: string indices must be integers
print(price)
I've tried many things:
from decimal import Decimal
price = decimal(fill['price'])
also:
price = int(fill['price']) # but it's not really an int
and:
price = float(fill['price']) # but sometimes it's a very big float so I need decimal
CodePudding user response:
It seems that what you get from the API is not exactly what you expect:
The variable fill
is a string (at least at the time you get the error).
As strings can't have string indices (like dictionaries can) you get the TypeError
exception.
To handle the exception and troubleshoot it, you can use try-except
, like so:
try:
price = fill['price']
except TypeError as e:
print(f"fill: {fill}, exception: {str(e)}")
This way, when there is an issue, the fill
value will be printed as well as the exception.
CodePudding user response:
string indices must be integers
tells you that the type of fill
during runtime at some point is a str
instead of Dict
. I suggest that you add type checking or assertion to your program to make sure fill
is of the expected type.
CodePudding user response:
If you want to just ignore it you could use try and except blocks.
try:
price = fill['price']
except Exception as e:
print(f"Error reading the price. Error: {e}")