How can I check if a value exists in a dictionary that is nested within a loop
Hi this is work for me
def check_exist(my_dict, key): if key in my_dict.keys(): return True return False
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=0indexgot=0for i in sVars: if(i['Itemname']=='item1'): flag=1 indexgot=iif(not flag): sVars.append({'Itemname': "item1", 'Itemprice': float(50), 'Qty': 0})else: sVars[sVars.index(indexgot)]['Qty'] += 1print(sVars)
just an approach ... to solve your problem.