我正在尝试使用.update()添加到python词典中

2024-05-18 19:14:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了一个字典ss,它包含特定股票的总股数。然后我需要做一些计算并创建一个新的字典temp,我将把它输入到我的.html页面中进行演示。更新功能无法按我的预期工作,因为temp中的所有内容都是最后一支股票,而不是我购买的所有股票的列表。当我打印ss时,有[{key:value,etc}],但是当我打印temp时,{key:value,etc}周围没有[]。我想我错过了一些基本的东西

另外,my.html页面没有读取临时字典,因为该页面为空。代码如下:

@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)

任何方向都很好。谢谢


Tags: dataindex字典valuehtml页面symbolss
3条回答

TL;博士

# 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
    }
})

有两种引用相关数据的通用方式,列表和字典。以最简单的方式考虑:

apple
orange
pear

使用基本语法语法,我们可以理解一个是“列举”它的部分的列表;邻接是每个单独部分之间有意义的关系。列表的上下文和使用与其外部(变量)上下文相关

另一方面,字典指定特定于定义列表的内容。考虑:

fruit: apple, orange, pear

这里,水果是对不同类型水果的计数;定义“水果”就是给外部(变量)上下文提供一个限定“水果”名称的列表。或:

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

也许是一个“真实”的定义

因此,如果我们考虑如何引用一个列表和一个字典,将一个列表添加到定义中,我们通过(通常)添加一个新的项:

创建一个新的列表
apple
orange
pear
+ kiwi

在我们有三个之前,现在我们有四个(上下文)

然而,我们通过指定其定义并命名来附加新定义:

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

如果需要,我们可以通过重新定义来更新fruit

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

这给了我们一本只包含其组成部分的词典:

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

因为您只能定义(和更新)内部引用(fruit

在psuedocode中,一个列表:

fruits = []

fruits.add('apple')
fruits.add('orange')
fruits.add('pear')

// ['apple','orange','pear']

同样,定义列表也适用于“键”关系,因此您可以添加或重新定义关系:

foods = {}

foods['fruit'] = 'I like fruit.'
foods['vegetables'] = 'Gotta eat your veggies.'

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

从这个意义上说,“更新”字典意味着重新定义和/或提供新的“键”关系(内部)

考虑:

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

那么,您真正需要的是词典的唯一键。独特之处在于,在词典的上下文中,一个键等于一个定义。我想它会是这样的:

# 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
    }
})

或直接:

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

现在,您正在使用定义有意义的术语更新词典,这些术语根据术语解析为特定的定义

ss中,每个股票已经有一个单独的行。记住,只需“声明”键/值对,就可以将它们添加到字典中,例如row["totval"] = {value}。提示,在SQL中尽可能多地选择,例如SQL中的符号、名称

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.

我认为你的类型不匹配,这是一个常见的错误。我不确定您对db.execute使用的是什么API/包,但该方法似乎将list[])分配给了ss。另一方面,您的temp值是一个dict,({})。我建议两种解决方案中的一种

如果render_template希望tempdict而不是list,请尝试以下操作,如DinoCoderSaurus{a2}:

def index():
    # other code here
    for row in ss:
        data = lookup(row["symbol"])
        totval = row["SUM(shares)"] * data["price"]

        # notice omission of data["symbol"] in temp1 assignment
        temp1 = { "name": data["name"], "shares": row["SUM(shares)"], "price": data["price"], "total value":totval }

        # assign temp1 to data["symbol"] key in new dict
        temp[data["symbol"]] = temp1 

另一方面,如果render_template期望templist一样ss,请尝试:

def index():
    # list to feed data into index (note change in data structure)
    temp = []

    # other code
    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.append(temp1)

相关问题 更多 >

    热门问题