Home > Software design >  Summarize price from items in dictionary
Summarize price from items in dictionary

Time:10-31

I'm struggling with making the program to summarize price of the products.

prices_and_their_products = {
    "Apple": 1,
    "Water": 2,
    "Grape": 3
}
shopping_list = ['Apple', 'Water']

I want the program to print "3".

The code I was trying to do it:

total = 0
for particular_items in shopping_list:
    total  = prices_and_their_products.get(particular_items)
    print(total)

I wont program to print the summary of products in "shopping_list". In this case: 3

CodePudding user response:

It seems to me the code you have now is fine. It does print 1 then 3 because print is indented inside of the for loop, so if you want it just to print 3 you could unindent the print statement so that it only runs after the loop.

#!/usr/bin/env python

prices_and_their_products = {
    "Apple": 1,
    "Water": 2,
    "Grape": 3
}
shopping_list = ['Apple', 'Water']

total = 0
for particular_items in shopping_list:
    total  = prices_and_their_products.get(particular_items)
print(total)
<script src="https://modularizer.github.io/pyprez/pyprez.min.js"></script>

There are ways it could be made more concise if you wish byt using a list_comprehension and the builtin sum function. In some cases list_comprehensions come at the expense of readability, but this case is simple enough that it works pretty well. Try this runnable example!

#!/usr/bin/env python

prices_and_their_products = {
    "Apple": 1,
    "Water": 2,
    "Grape": 3
}
shopping_list = ['Apple', 'Water']
cost = sum(prices_and_their_products[item_name] for item_name in shopping_list)
print(f"{cost=}")
<script src="https://modularizer.github.io/pyprez/pyprez.min.js"></script>

CodePudding user response:

Your code has a small indentation bug in it. Your print statement should not be inside the for loop or it will print the total for each iteration of the loop.

prices_and_their_products = {
    "Apple": 1,
    "Water": 2,
    "Grape": 3
}
shopping_list = ['Apple', 'Water']

total = 0
for particular_items in shopping_list:
    total  = prices_and_their_products.get(particular_items)
print(total)

CodePudding user response:

just take the print outside the loop :

total = 0
for particular_items in shopping_list:
    total  = prices_and_their_products.get(particular_items)
print(total)

CodePudding user response:

Thank you for help. Now everything works as i want.

  • Related