簡體   English   中英

如何從詞典列表中修改詞典的值

[英]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.

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