簡體   English   中英

如何檢查嵌套在循環中的字典中是否存在值

[英]How can I check if a value exists in a dictionary that is nested within a loop

如果項目名稱已經在嵌套在列表中的字典中,則我嘗試增加數量值。我計划使用的方法是通過檢查字典中是否不存在項目名稱,然后將其添加到列表中,否則它確實存在於字典中,然后將數量更新一。

我不太確定如何檢查項目名稱是否在嵌套字典中,即環顧四周但未找到任何內容

@app.route("/AddToCart", methods=["POST", "GET"])
def addToCart():
    itemId = int(request.form.get("productId"))
    MenuItem = Menu.query.get(itemId)

    if MenuItem is None:
        return render_template("error.html", errorMessage="There has been an issue adding this item to your basket")

    sVars = session['cart']

    if(MenuItem.ItemName not in sVars):
        sVars.append({'Itemname': MenuItem.ItemName, 'Itemprice': float(MenuItem.ItemPrice), 'Qty': 0})
    else:
        sVars['Qty'] += 1

    session['cart'] = sVars

    allPrices = Money(amount=sum([x['Itemprice'] for x in sVars]), currency='GBP')

    return render_template("cart.html", cartSession=session['cart'],allPrices=allPrices)

嗨,這是我的工作

def check_exist(my_dict, key):
    if key in my_dict.keys():
        return True
    return False

一種簡單的方法是替換這段代碼:

    sVars = session['cart']

    if(MenuItem.ItemName not in sVars):
        sVars.append({'Itemname': MenuItem.ItemName, 'Itemprice': float(MenuItem.ItemPrice), 'Qty': 0})
    else:
        sVars['Qty'] += 1

    session['cart'] = sVars

    allPrices = Money(amount=sum([x['Itemprice'] for x in sVars]), currency='GBP')

    return render_template("cart.html", cartSession=session['cart'],allPrices=allPrices)

與:

    cart = session['cart']
    for item in cart:
        if item['Itemname'] == MenuItem.ItemName:
            item['Qty'] += 1
            break
    else:
        cart.append({
            'Itemname': MenuItem.ItemName,
            'Itemprice': float(MenuItem.ItemPrice),
            'Qty': 1
        })

    totalPrice = Money(
        amount=sum([item['Itemprice'] * item['Qty'] for item in cart]), 
        currency='GBP')

    return render_template("cart.html", cartSession=cart, allPrices=totalPrice)

一些注意事項:首先,您的原始代碼嘗試將sVars 用作數組(帶有.append() ),又用作字典(帶有sVars['Qty'] )。 當然,它必須是一個。 我假設它是一個數組,但是如果該假設是錯誤的,請更正我(並顯示它的示例)。

其次,我建議的代碼使用許多人都不熟悉的Python功能,一個帶有for循環的else塊。 如果您以前從未看到過此功能,那么它就是專門為這種用途而設計的。 它的工作方式是,如果使用break語句顯式退出循環,則不會執行else塊。 如果循環運行到結束,那么else執行。

最后,我假設allPrices應該是購物車中所有項目的總價,因此每個項目的價格應乘以其數量。

假設您有一個這樣的列表:

ls = [{"Itemname": "Test", "Itemprice": 1, "Qty": 0}, {"Itemname": "Test1", "Itemprice": 1, "Qty": 0}]

那么您可以使用像這樣的功能來更新商品:

def updateItems(inpdic):
    for item in ls:
        if item["Itemname"] == inpdic["Itemname"]:
            item["Qty"] += 1
            return
    ls.append(inpdic)

您可以遍歷列表中的所有項目,如果存在相同名稱的項目,則增加數量並退出,否則將其追加。

sVars=[]


flag=0
indexgot=0

for i in sVars:
    if(i['Itemname']=='item1'):
        flag=1
        indexgot=i


if(not flag):
    sVars.append({'Itemname': "item1", 'Itemprice': float(50), 'Qty': 0})
else:
    sVars[sVars.index(indexgot)]['Qty'] += 1

print(sVars)

只是解決您問題的一種方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM