简体   繁体   中英

How to sum of values in dict? Python, Flask

I have simple shopping cart created via session in Flask:

session['cart'] += [{
    'product_name': request.form['product_name'],
    'product_cost': request.form['product_cost'],
    'product_img': request.form['product_img'],
}]

So how can get sum of values in product_cost ?

I tried do that to get value of product_cost :

for products in cart_products:
    for p in products:
        print(p.product_cost)

But I get an error: AttributeError: 'str' object has no attribute 'product_cost'

Output of print(cart_products) , where cart_products = session['cart'] :

{'product_name': 'product2', 'product_cost': '400', 'product_img': '*very long binary object*'}

Regarding your edit, note that this is actually a dictionary:

product_cart = {'product_name': 'product2', 'product_cost': '400', 'product_img': ''}

So the cost is accessible via product_cart['product_cost'] .

However I'm not sure if you really mean to maintain this as a list of dictionaries (where the list is the cart contents, and each dictionary is a product. That would look like:

product_cart = [{'product_name': 'product1', 'product_cost': '300', 'product_img': ''},
                {'product_name': 'product2', 'product_cost': '400', 'product_img': ''},
                {'product_name': 'product3', 'product_cost': '300', 'product_img': ''},
                ]

You could then do:

>>> for product in product_cart:
...  print (product['product_cost'])
... 
300
400
300

So to get the some of all the values, have a function like:

def get_cart_total(cart):
     return sum([float(product['product_cost']) for product in cart ])

Note this turns the string values like '400' to type float . Use it like:

>>> get_cart_total(product_cart)
1000.0

Using the first for loop you are accessing the dictionaries but the problem is, you are accessing the keys inside the dictionary instead of the values using the second for loop. So instead just do this:

for products in cart_products:
    print(products['product_cost'])

To get the sum of product_cost you would need:

 sum([int(x['product_cost']) for x in session['cart']])

Example:

cart = [
    {
        'product_name': 'abc',
        'product_cost': 12,
        'product_img': 'abc.jpg',
    },
    {
        'product_name': 'abc',
        'product_cost': 13,
        'product_img': 'abc.jpg',
    },
    {
        'product_name': 'abc',
        'product_cost': 14,
        'product_img': 'abc.jpg',
    },
]

total = sum([x['product_cost'] for x in cart])
print(total)

->

39

You can try to use

some_var = session[‘cart’][0].values()
another_var = len(some_var)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM