简体   繁体   English

如何检查嵌套在循环中的字典中是否存在值

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

I am trying to increment the quanitity value if the item name is already in the dictionary nested within a list, the method I was planning on using is by checking if itemname doesn't already exists in the dictionary then add to the list, else if it does exist in the dictionary then update thw quantity by one. 如果项目名称已经在嵌套在列表中的字典中,则我尝试增加数量值。我计划使用的方法是通过检查字典中是否不存在项目名称,然后将其添加到列表中,否则它确实存在于字典中,然后将数量更新一。

I'm not too sure how to check to see if the itemname is in the nested dictionary iv'e looked around but haven't found anything 我不太确定如何检查项目名称是否在嵌套字典中,即环顾四周但未找到任何内容

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

Hi this is work for me 嗨,这是我的工作

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

One easy way to do this would be to replace this section of code: 一种简单的方法是替换这段代码:

    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)

with: 与:

    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)

Some notes: First, your original code tries to use sVars both as an array (with .append() ) and as a dictionary (with sVars['Qty'] ). 一些注意事项:首先,您的原始代码尝试将sVars 用作数组(带有.append() ),又用作字典(带有sVars['Qty'] )。 It has to be one or the other, of course. 当然,它必须是一个。 I am assuming that it is an array, but correct me if that assumption is wrong (and show an example of it). 我假设它是一个数组,但是如果该假设是错误的,请更正我(并显示它的示例)。

Second, my suggested code uses a Python feature that many are unfamiliar with, an else block with a for loop. 其次,我建议的代码使用许多人都不熟悉的Python功能,一个带有for循环的else块。 If you haven't see this before, it's designed for just this kind of use. 如果您以前从未看到过此功能,那么它就是专门为这种用途而设计的。 The way it works is that if the loop is explicitly exited with a break statement, the else block is not executed. 它的工作方式是,如果使用break语句显式退出循环,则不会执行else块。 If the loop runs to completion, then the else block is executed. 如果循环运行到结束,那么else执行。

Finally, I assume that allPrices should be the total price of all items in the cart, so each item's price should be multiplied by its quantity. 最后,我假设allPrices应该是购物车中所有项目的总价,因此每个项目的价格应乘以其数量。

assuming you have a list like this: 假设您有一个这样的列表:

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

then you could have a function like this to update the items: 那么您可以使用像这样的功能来更新商品:

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

you go over all the items in the list, if an item with the same name exists you increase the quantity and exit, otherwise you append it. 您可以遍历列表中的所有项目,如果存在相同名称的项目,则增加数量并退出,否则将其追加。

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)

just an approach ... to solve your problem. 只是解决您问题的一种方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM