![](/img/trans.png)
[英]how to create a dictionary with list of dictionaries as values from a list of dictionaries
[英]How to modify the values of a dictionary from a list of dictionaries
我在声明一个名为add_to_cart的方法(db,itemid,数量)。 每当调用该方法时,它将在数据库中查找会话数据。 会话数据包含词典列表。 此方法的目的是为列表创建一个新条目(字典)或更新现有条目的值。 字典具有以下键:id,数量
到目前为止,我已经开发了以下代码。 首先,从数据库中获取数据后,我将itemid与字典键“ id”进行匹配。 如果itemid与字典的任何值都不匹配,则它将新字典添加到该列表。
def add_to_cart(db, itemid, quantity):
# ......
row = cursor.fetchone()
if row is not None:
cart = json.loads(row['data'])
for dic in cart:
if str(dic.get("id")) == str(itemid):
dic['quantity'] = int(dic['quantity']) + quantity
data = json.dumps(cart)
# update the 'data' to the database
break
else:
if counter == len(cart):
item = {
'id': itemid,
'quantity': quantity
}
cart.append(item)
data = json.dumps(cart)
# update the 'data' to the database
break
让最初的购物车像:
[{'id':'40','quantity':'2'},{'id':'41','quantity':'5'}]
当我在购物车中再添加1件商品40时,应该像这样:
[{'id':'40','quantity':'3'},{'id':'41','quantity':'5'}]
但我得到:
[{'id':'40','quantity':'2'},{'id':'41','quantity':'5'},{'id':'40','quantity': '1'}]
您在执行cart.append(item)
时将新字典添加到列表中,因此该列表
[{'id': '40', 'quantity': '2'}, {'id': '41', 'quantity': '5'}]
最终成为
[{'id': '40', 'quantity': '2'}, {'id': '41', 'quantity': '5'}, {'id': '40', 'quantity': '1'}]
但是您想在该词典列表中找到匹配的ID,然后将其添加到该词典的数量中。
因此,代码如下所示:
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'}]
问题似乎是您将通过append
将一个新的dict简单地添加到列表(购物车)中。 您需要浏览列表,找到具有所需itemid
的字典,然后将其添加到quantity
。
尝试这个 -
for dict in cart:
if dict[itemid] == itemid:
dict['quantity'] += str(quantity)
break
item = {
'id': itemid,
'quantity': quantity
}
cart.append(item)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.