Skip to content Skip to sidebar Skip to footer

Typeerror: String Indices Must Be Integers. Python, Flask

I have a simple cart created via session in Flask: session['cart'] += [{ 'product_name': request.form['product_name'], 'product_cost': request.form['product_cost'], 'pr

Solution 1:

Something doesn't add up (no pun intended) here:

full_cost = sum([int(product['product_cost']) for product in cart_products ])
TypeError: string indices must be integers

When the product_cart in your question is supplied as the input to this it should work.

However if you had a string as a member of the product_cart list, instead of a dictionary it would throw this exception:

>>> product_cart = ['test']
>>>sum([int(product['product_cost']) for product in product_cart ])
Traceback (most recent calllast):
  File "<stdin>", line 1, in<module>
  File "<stdin>", line 1, in<listcomp>
TypeError: string indices must be integers

Or to put it another way:

>>> {'product_cost':'123'}['product_cost']
'123'
>>> 'some_string'['product_cost']
Traceback (most recent call last):
  File"<stdin>", line 1, in <module>
TypeError: string indices must be integers

So the exception you're seeing in your code is because the list comprehension within the sum function, is getting a string for product.

Something is not as it seems within your session['cart'] so it's impossible for anyone to solve with the info given in this question, sorry.

Post a Comment for "Typeerror: String Indices Must Be Integers. Python, Flask"