Home > front end >  Getting sum of values from Dicts in a List
Getting sum of values from Dicts in a List

Time:07-14

order = [{"name": 'espresso', "price": 1.99},
         {"name": 'coffee', "price": 2.50},
         {"name": 'cake', "price": 2.79},
         {"name": 'soup', "price": 4.50},
         {"name": 'sandwich', "price": 4.99}]

I need to get the sum of the order and put that sum in a variable called subtotal. I understand I need a for loop through the list but don't know how to grab the value associated with "price" in each dict and sum them all up.

CodePudding user response:

Use the built-in sum function to sum the list, and we create the list using list comprehension.

subtotal = sum([d["price"] for d in order])

Good day.

CodePudding user response:

You can use square brackets to get the price:

# Prints out all the prices
for x in order:
    print(x['price'])

Now, all you have to do is add this to a variable called subtotal

# Adds prices to subtotal and outputs 16.77
subtotal = 0.0
for x in order:
    subtotal  = x['price']
print(subtotal)

Or, more simply:

# Uses a comprehension along with sum (again outputs 16.77)
subtotal = sum(x['price'] for x in order)
print(subtotal)

CodePudding user response:

you can do that using square brackets and the iadd operation ( =):

subtotal = 0
for x in price:
    subtotal  = x["price"]

A faster way of accomplishing that would also be to use the sum function and using a generator comprehension that is faster as suggested in the comments by @b.d:

subtotal = sum(x["price"] for x in price)

on other answers

I saw this by @JudeDavis the answers one who does it also using list comprehension:

subtotal = sum([x["price"] for x in price])

it's literally the same thing as the code provided above but by interpreter optimizations the generator comprehension is faster long story short, the list has 2 features:

  • mutable
  • supports non-unique items

but the tuple supports only non-unique items so it's a little bit faster with some optimization done by python(not getting into details).

CodePudding user response:

Use the built-in sum function to sum it up.

But instead of summing over a list, use a generator instead for optimized code.

subtotal = sum(d["price"] for d in order)

PS: Notice that the sum function is not performed on a list (and is a generator instead) like in the answer provided by @JudeDavis

  • Related