[SOLVED] Calculating sum of ordered list of dictionaries


This Content is from Stack Overflow. Question asked by David A Quintanilla

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():
    order = []
    count = 1
    for i in range(3):
        item = input('Select menu item number ' + str(count) + ' (from 1 to 5): ')
        count += 1
    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?


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]

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

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 4.0.

people found this article helpful. What about you?