Вы добавляете новый словарь в список, когда делаете cart.append(item)
,
отсюда и список
[{'id': '40', 'quantity': '2'}, {'id': '41', 'quantity': '5'}]
в итоге становится
[{'id': '40', 'quantity': '2'}, {'id': '41', 'quantity': '5'}, {'id': '40', 'quantity': '1'}]
Но вы хотите найти соответствующий идентификатор в этом списке словарей и добавить к количеству для этого словаря.
Таким образом, код будет выглядеть следующим образом:
li = [{'id': '40', 'quantity': '2'}, {'id': '41', 'quantity': '5'}]
def add_elem(li, id, to_add):
#Iterate over the dictionaries
for item in li:
#If the id is found
if str(id) in item.values():
#Increment the quantity
item['quantity'] = str(int(item['quantity']) + to_add)
#Return the updated list
return li
print(add_elem(li, 40, 1))
Выход будет
[{'id': '40', 'quantity': '3'}, {'id': '41', 'quantity': '5'}]