Summing values from a nested dictionary

Question:

Does anyone know how to sum all the values, for all the items, in ‘total_price’.

My best attempt below, I got as far as getting the values but couldn’t sum them together.

It would be great if someone could tell me how to do it. (Code is condensed btw – part of a much larger, work in progress, program).

order_dictionary = {'Ham & Cheese': {'quantity': 2, 'price': 5, 'total_price': 10}, 'Hawaiian': {'quantity': 4, 'price': 5, 'total_price': 20}}

print("n" + "*"*60 + "nYour order:" + "n")
for items in order_dictionary.items():
    idx, item = items
    print(f" {idx: <27} x{int(item['quantity']): <6}   ${item['total_price']:.2f}n")
for food, info in order_dictionary.items():
    total = info['total_price']
Asked By: ReZ Cheetah

||

Answers:

It looks like you have found each individual 'total_price' value. Now you just need to add them up:

total = 0
for food, info in order_dictionary.items():
    total += info['total_price']
print(total)

Output

30

Answered By: quamrana

You can sum total after iterating over dictionary. You can compute total in the first loop and you don’t need to write another loop. (values in the nested dict are int and you don’t need to convert to int.)

order_dictionary = {'Ham & Cheese': {'quantity': 2, 'price': 5, 'total_price': 10}, 'Hawaiian': {'quantity': 4, 'price': 5, 'total_price': 20}}

total = 0
print("n" + "*"*60 + "nYour order:" + "n")
for idx, item in order_dictionary.items():
    print(f" {idx: <27} {item['price']} x {item['quantity']: <6}   ${item['total_price']:.2f}n")
    total += item['total_price']

print(f" total {' ': <34} ${total:.2f}")

************************************************************
Your order:

 Ham & Cheese                5 x 2        $10.00

 Hawaiian                    5 x 4        $20.00

 total                                    $30.00
Answered By: I'mahdi

You are almost there!

order_dictionary = {'Ham & Cheese': {'quantity': 2, 'price': 5, 'total_price': 10}, 'Hawaiian': {'quantity': 4, 'price': 5, 'total_price': 20}}

print("n" + "*"*60 + "nYour order:" + "n")

# Initialise a total variable
total = 0

# This shows order recap
for items in order_dictionary.items():
    idx, item = items
    print(f" {idx: <27} x{int(item['quantity']): <6}   ${item['total_price']:.2f}n")
    
    # Update the total during the loop
    total += int(item['quantity']) * item['price']
    
print(f"Order total: ${total}")

N.B. Please note that you actually do not need to store "total_price" as it’s redundant (you can calculate it as unitary price * quantity).

Answered By: decadenza
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.