Search code examples
pythonindexingcs50finance

I am trying to add to a dictionary in python using .update()


I create a dictionary, ss, which has a total number of shares for a specific stock. Then I need to do some calculations and create a new dictionary, temp, which I will feed into my .html page for presentation. The update function does not work as I intend because all that is in temp is the last stock, not a listing of all the stocks I have purchased. When I print ss, there is [{key:value, etc}], but when I print temp there is no [ ] around the {key:value, etc}. I think I am missing something basic.

Also my .html page is not reading the temp dictionary as the page is empty. Here is the code:

@app.route("/")
@login_required
def index():
    """Show portfolio of stocks"""
    #dictionary to feed data into index
    temp={}
    #Select from trades all stocks held by this user
    ss = db.execute("SELECT SUM(shares), symbol FROM trades WHERE id=? GROUP BY symbol", session["user_id"])
    print(ss)
    #lookup current price for each stock and create index of all stocks held
    for row in ss:
        data=lookup(row["symbol"])
        totval=row["SUM(shares)"]*data["price"]
        temp1={"symbol":data["symbol"], "name":data["name"], "shares":row["SUM(shares)"], "price":data["price"], "total value":totval}
        temp.update(temp1)
        
    print(temp)
    return render_template("index.html", temp=temp)

Any direction would be great. Thanks.


Solution

  • TL;DR

    # Note use of the data["symbol"]
    temp.update({
        data["symbol"]: {
            "symbol": data["symbol"],
            "name": data["name"],
            "shares": row["SUM(shares)"],
            "price": data["price"],
            "total value": totval
        }
    })
    

    There are two generic manners of referencing related data, lists and dictionaries. In the simplest manner, consider:

    apple
    orange
    pear
    

    Using basic grammatical syntax, we can understand one is a list that "enumerates" it's part; the adjacency is the meaningful relationship between each individual part. The context and use of the list relates to it's external (variable) context.

    A dictionary, on the other hand, specifies something specific is contextual to the list of definitions specifically. Consider:

    fruit: apple, orange, pear
    

    Here, fruit is an enumeration of different types of fruit; to define "fruit" is to give a list of qualifying "fruit" names contextual to an external (variable) context. Or:

    fruit: An edible, usually sweet and fleshy form of such a structure.
    

    Maybe a "real" definition.

    So if we consider how we would refer to a list versus a dictionary, to add definitions to a list, we create a new list by (generally) appending a new item:

    apple
    orange
    pear
    + kiwi
    

    Before we had three, now we have four (contextually).

    Whereas we append a new definition by specifying it's definition and naming it:

    fruit: An edible, usually sweet and fleshy form of such a structure.
    + vegetable: A plant cultivated for its edible parts.
    

    We could, if we want, update fruit by redefining it:

    fruit: An edible, usually sweet and fleshy form of such a structure.
    vegetable: A plant cultivated for its edible parts.
    + fruit: I like fruit.
    

    Which gives us a dictionary of only it's constituent parts:

    vegetable: A plant cultivated for its edible parts.
    fruit: I like fruit.
    

    Because you can only define (and update) the internal reference (fruit).

    In psuedocode, a list:

    fruits = []
    
    fruits.add('apple')
    fruits.add('orange')
    fruits.add('pear')
    
    // ['apple','orange','pear']
    

    Likewise, a definition list works on the "key" relationship, and thus you may add or redefine a key relation:

    foods = {}
    
    foods['fruit'] = 'I like fruit.'
    foods['vegetables'] = 'Gotta eat your veggies.'
    
    // {
    //    fruit: 'I like fruit.',
    //    vegetables: 'Gotta eat your veggies!',
    // }
    

    In this sense, "updating" a dictionary means redefining and/or providing a new "key" relationship (internally).

    Consider:

    fruits = []
    
    fruits.append('apple')
    fruits.append('orange')
    fruits.append('pear')
    
    print(', '.join(fruits))
    
    # apple, orange, pear
    
    foods = {
        'fruits': 'Fruits are good.'
    }
    
    # Adding a definition
    foods['vegetables'] = 'Gotta eat your veggies!'
    
    # Updating a definition
    foods.update({
        'fruits': 'I like fruit!',
        'meats': 'Can haz meat?'
    })
    
    for food in foods.values():
        print(food)
    
    # I like fruit!
    # Gotta eat your veggies!
    # Can haz meat?
    

    https://onlinegdb.com/SkneEJsw_

    What you really need, then, are unique keys for your dictionary. Unique in the sense that within the dictionary's context, one key equals one definition. Which I think will look this:

    # Note use of the data["symbol"]
    temp.update({
        data["symbol"]: {
            "symbol": data["symbol"],
            "name": data["name"],
            "shares": row["SUM(shares)"],
            "price": data["price"],
            "total value": totval
        }
    })
    

    Or directly:

    temp[data["symbol"]] = {
        "symbol": data["symbol"],
        "name": data["name"],
        "shares": row["SUM(shares)"],
        "price": data["price"],
        "total value": totval
    }
    

    Now you're updating your dictionary with meaningfully defined terms that resolve to a specific definition based on a key term.