Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append existing keys by value in python dictionary?

Tags:

python

flask

I'm trying to create a shopping cart based on sessions on Flask.

Idea is simple:

  1. Customer clicks "Add to cart" button with hidden inputs product_id and qty
  2. This POST query adds new record in session["cart"] dictionary

    [{'qty': '1', 'product_id': '6'}, 
    {'qty': '1', 'product_id': '6'},
    {'qty': '1', 'product_id': '6'}]
    
  3. I catch this fields and append them in session dict by:

    session["cart"].append(dict({'product_id': id, 'qty': qty}))
    

Every time someone add product in cart it add new record {'product_id': id, 'qty': qty} in cart session.

How to check if this product_id already in dictionary and if it does, increment just qty but don't create new record in dictionary with same product_id?

My Add to cart:

@app.route('/add-to-cart', methods=['GET', 'POST'])
def add_to_cart():
    if request.method == 'POST':
        id = int(request.form['product_id'])
        qty = int(request.form['qty'])

        cart_session()

        matching = [d for d in session['cart'] if d['product_id'] == id]
        if matching:
            matching[0]['qty'] += qty

        session["cart"].append(dict({'product_id': id, 'qty': qty}))

        return redirect(url_for('home'))

Solution

@app.route('/add-to-cart', methods=['GET', 'POST'])
def add_to_cart():
    if request.method == 'POST':
        id = int(request.form['product_id'])
        qty = int(request.form['qty'])

        cart_session()

        matching = [d for d in session['cart'] if d['product_id'] == id]
        if matching:
            matching[0]['qty'] += qty
        else:
            session["cart"].append(dict({'product_id': id, 'qty': qty}))

        return redirect(url_for('home'))
like image 913
Denis Avatar asked Apr 10 '26 04:04

Denis


1 Answers

One easy way in python to look for objects in a list is to use list comprehension:

matching = [d for d in session['cart'] if d['product_id'] == id]
if matching:
    matching[0]['qty'] += int(qty)
else:
    session['cart'].append(dict({'product_id': id, 'qty': int(qty)}))
like image 161
Djizeus Avatar answered Apr 12 '26 16:04

Djizeus