Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Summing values from a nested dictionary

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).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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']

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading