【问题标题】:How to modify the values of a dictionary from a list of dictionaries如何从字典列表中修改字典的值
【发布时间】:2019-10-06 22:44:41
【问题描述】:

我声明了一个名为 add_to_cart(db, itemid, quantity) 的方法。每当调用该方法时,它都会在数据库中查找会话数据。会话数据包含字典列表。此方法的目的是为列表创建一个新条目(字典)或更新现有条目的值。 字典有以下键: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', '数量': '1'}]

【问题讨论】:

    标签: python mysql python-3.x sqlite


    【解决方案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'}]
    

    【讨论】:

      【解决方案2】:

      问题似乎是您只是通过append 将新字典添加到列表(购物车)中。您需要遍历列表,找到您需要的带有itemid 的dict,然后添加到quantity

      试试这个 -

      for dict in cart:
           if dict[itemid] == itemid:
              dict['quantity'] += str(quantity)
              break
      
      item = {
              'id': itemid,
              'quantity': quantity
             }
      cart.append(item)
      

      【讨论】:

        猜你喜欢
        • 2016-09-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-03
        • 2020-11-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多