1

I've been stuck on this for quite some time. I believe that I'm getting back data in the form of a dictionary but can't figure out how to get the information that I need.

Error messages that have shown up are:

(1) symbol = dict["symbol"] - list indices must be integers or slices, not str

(2) {% for symbol in dict %} - type' object is not iterable

def index():
"""Show portfolio of stocks"""
dict = db.execute("SELECT symbol, amount FROM holdings WHERE id=:id", id=session["user_id"])
cash = db.execute("SELECT cash FROM users WHERE id=:id", id=session["user_id"])[0]["cash"]

overalltotal = cash

for symbol in dict:
    symbol = dict["symbol"]
    amount = dict["amount"]
    
    info = lookup(symbol)
    price = float(info["price"])
    value = float(price * amount)
    overalltotal = overalltotal + value
    
return render_template("index.html", cash = cash, overalltotal = overalltotal)

And here is my html:

 <div>
    <table class="table">
        <tr>
            <th>Stocks</th>
            <th>Number</th>
            <th>Current Price</th>
            <th>Total Value</th>

        </tr>
        {% for symbol in dict %}
        <tr>
            <td> {{ symbol.symbol }}</td>
            <td> {{ symbol.amount }}</td>
            <td> {{ symbol.price }}</td>
            <td> {{ symbol.value }}</td>
        </tr>
        Cash: {{ cash }} <br>
        Total: {{ overalltotal }}
        {% endfor %}
    </table>
</div>

If anyone could be able to explain what I have done wrong, I would greatly appreciate it.

1
  • To update, I ended up changing up the code a little bit, but turns out one of my main errors was that I needed a unique index in my holdings table. Before I had id and symbol be a composite primary key, but now I remade the sql table with uniqueindex to be the sole key, did uniqueindex["symbol"] and uniqueindex["amount"], and the code worked like a charm!
    – ddinh9978
    Aug 8 '20 at 19:09
0

For your first error, the problem is that dict is a list of dictionaries, so when you are calling dict["symbol"] you get an error message. To get the answer you want, use symbol["symbol"] inside the for loop.
As for your second error, you should use the same syntax as above, so for symbol.symbol it should be symbol["symbol"] and for symbol.amount it should be symbol["amount"], etc.

1
  • I have implemented the changes that you have suggested but this time, the terminal window returns : amount = symbol["amount"] - TypeError: string indices must be integers
    – ddinh9978
    Aug 8 '20 at 16:45

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .