Home > OS >  python: how to use dictionary and for loop to work out total cost for a list of (item, quantity) tup
python: how to use dictionary and for loop to work out total cost for a list of (item, quantity) tup

Time:03-04

this is my first time using stack overflow as I am just starting to learn python so apologies if I don't phrase things as clearly as I should!

I am working on a problem which asks me to set up a stationery shop. There is a dictionary with prices:

stationery_prices = {
    'pen': 0.55,
    'pencil': 1.55,
    'rubber': 2.55,
    'ruler': 3.55
}

I have to ask the user to input what item they would like and what quantity, and then arrange this in a list of tuples.

So now I have a list that looks like this:

[('pen', 1), ('pencil', 2)]

How do I use a for loop to refer back to the original dictionary of prices and add up the total cost for the user?

Thank you very much

CodePudding user response:

Iterate over each element, unpacking the tuple:

total = 0
for bought_item in bought_items:
    item_name = bought_item[0]
    quantity = bought_item[1]
    total  = stationery_prices[item_name] * quantity

print(total)

Note that this is more verbose than necessary (e.g. no tuple unpacking in the for loop). I chose to do this to reduce possible confusion with unfamiliar syntax. If you wanted to do it in one line, you could do:

total = sum(stationery_prices[item_name] * quantity 
    for item_name, quantity in bought_items)
  • Related