Calculating sum of ordered list of dictionaries

Question:

I am trying to find out how to return a sum of several values given in a order list of dictionaries

menu = {
    1: {"name": 'espresso',
        "price": 1.99},
    2: {"name": 'coffee', 
        "price": 2.50},
    3: {"name": 'cake', 
        "price": 2.79},
    4: {"name": 'soup', 
        "price": 4.50},
    5: {"name": 'sandwich',
        "price": 4.99}
}


def calculate_subtotal(order):
  
return subtotal

def take_order():
    display_menu()
    order = []
    count = 1
    for i in range(3):
        item = input('Select menu item number ' + str(count) + ' (from 1 to 5): ')
        count += 1
        order.append(menu[int(item)])
    return order
  • def calculate_subtotal(order) should accept one argument which is the order list and return the sum
    of the prices of the items in the order list.
  • Do I have to use a for loop to iterate through the values and sum each value?
  • How do I access the dictionaries inside the list?

Answers:

Let’s say a person orders the following:

orders = [
    {"name": "espresso", "price": 1.99},
    {"name": "espresso", "price": 1.99},
    {"name": "soup", "price": 4.99},
]

You now have a list of dict. Indexing into the list returns a reference to a dictionary. For example:

first_order = orders[0]
print(first_order)

Would print:

{'name': 'espresso', 'price': 1.99}

Using that knowledge, you can loop through the orders like so:

total = 0.0
for order in orders:
    total += order["price"]

Each order will be a dict like you saw above.

You can also use a comprehension if you’re comfortable with them.

total = sum(order["price"] for order in orders)
Answered By: Joshua Megnauth
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.