Home > Net >  Python .update() shopping cart list of dictionaries with updated quantity
Python .update() shopping cart list of dictionaries with updated quantity

Time:11-27

How can I get an updated value back into my shopping cart? I'm already checking to see if the product exists in the cart, and updating the new value in add_product.update(). I only want to add this new value (a "new" "existing" quantity) back into cart_products. Fully runnable code which prints the new value. Any help is appreciated.

What I've tried

  1. .update() = AttributeError: 'list' object has no attribute 'update'

    cart_products.update({'prod_quantity': matching_product[0]['prod_quantity']}, {'prod_quantity': update_quantity})

  2. .clear() = IndexError: list index out of range

    matching_product.clear() cart_products.append(add_product)

Python code

def product_exists(product: dict, cart: list):
    added_id = product.get("prod_id")
    in_cart = [existing_prod for existing_prod in cart if existing_prod.get("prod_id") == added_id] 
    if in_cart and len(in_cart) > 0:
        return True, in_cart
    return False, None

add_product = {'prod_id': 18, 'prod_name': 'Cat', 'prod_price': 30, 'prod_quantity': 2}
matching_product = [{'prod_id': 18, 'prod_name': 'Cat', 'prod_price': 30, 'prod_quantity': 1}]
cart_products = [{'prod_id': 15, 'prod_name': 'Penguin', 'prod_price': 40, 'prod_quantity': 1}, {'prod_id': 16, 'prod_name': 'Lion', 'prod_price': 20, 'prod_quantity': 2}, {'prod_id': 16, 'prod_name': 'Lion', 'prod_price': 20, 'prod_quantity': 4}, {'prod_id': 17, 'prod_name': 'Whale', 'prod_price': 20, 'prod_quantity': 1}, {'prod_id': 18, 'prod_name': 'Cat', 'prod_price': 30, 'prod_quantity': 1}]

exists, matching_product = product_exists(add_product, cart_products)

if exists: # If product exists in cart
    update_quantity = matching_product[0]['prod_quantity']   add_product['prod_quantity']
    print(update_quantity)
    print(matching_product[0]['prod_name'])
    add_product.update({'prod_quantity': update_quantity})
    print(add_product)
    # Code to update shopping cart with new quantity

else:
    cart_products.append(add_product)

CodePudding user response:

You could do something like this:

cart_products = [add_product if item['prod_id'] == add_product['prod_id'] else item for item in cart_products]

This will leave the elements of the cart_products as they are and will only replace the one which has prod_id the same as the add_product. In that case it will replace the original element with add_product.

  • Related