微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决我正在尝试使用 .update() 在 python 中添加字典

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

此外,我的 .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)

任何方向都很棒。谢谢。

解决方法

ss 中的每只股票都有单独的一行。请记住,键/值对可以通过“声明”它们非常简单地添加到字典中,例如row["totval"] = {value}。提示,SQL中尽量选择SELECT,例如sql中的symbol,name。

,

当我打印 ss 时,有 [{key:value,etc}],但当我打印 temp 时,[] 周围没有 {key:value,etc}。我想我缺少一些基本的东西。

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

如果 render_template 期望 tempdict 而不是 list,试试这个,如 DinoCoderSaurus suggests

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"],"total value": totval }
        temp.append(temp1)
,

TL;博士

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

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

apple
orange
pear

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

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

fruit: apple,orange,pear

这里,fruit 是对不同类型水果的枚举;定义“水果”就是给出一个与外部(变量)上下文相关的符合条件的“水果”名称列表。或者:

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

在伪代码中,一个列表:

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,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"],"total value": totval
    }
})

或直接:

temp[data["symbol"]] = {
    "symbol": data["symbol"],"total value": totval
}

现在,您正在使用有意义的术语更新字典,这些术语基于术语解析为特定的定义

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。