Search code examples
loopsdictionarytuples

Assigning to new variable by iterating through Tuples to find Dictionary Values


I've been asked to iterate through this list of tuples, grab [0] from each tuple and use that to pull the names.values(), which is then assigned to the 'receipt' list. Initial code below:

order_list = [("tom", 0.87, 4),
              ("sug", 1.09, 3),
              ("ws", 0.29, 4),
              ("juc", 1.89, 1),
              ("fo", 1.29, 2)]

# This dictionary gives the full name of each product code.
names = {"tom": "Tomatoes",
         "sug": "Sugar",
         "ws": "Washing Sponges",
         "juc": "Juice",
         "fo": "Foil"}

budget = 10.00
running_total = 0
receipt = []

Here is what I've come up with so far (there is another part which checks running total against budget but I've got that part covered so not mentioning that).

for i in order_list:
  if running_total <= budget:
    receipt += names[i[0]]
    running_total += (i[1] * i[2])
    budget - running_total
  else:
    print(f"You can't afford this item:, your running total is now {running_total}")

What I find happens is that the receipt ends up being an infinite loop of the given dictionary values... How do I write it so it's only added once... and how do I then include that particular item into the last print statement (the result should be Foil)...

I hope this makes sense.

By adding: receipt += names[i[0]] This just adds the dictionary values infinite amounts of times, rather than just once up until the point where the budget is exceeded...

By writing: print(f"You can't afford this item: {receipt}, your running total is now {running_total}") It just adds the infinitely added amount, and not sure how to get the specific item that triggers the else statement.


Solution

  • You should check if the cost (i[1] * i[2]) of the item doesn't exceed your remaining budget. You're proceeding to buy the item as soon as you have money left, making you spend more than your budget:

    for i in order_list:
      item = names[i[0]]
      cost = (i[1] * i[2])
      if running_total + cost <= budget:
        receipt.append(item)
        running_total += cost
      else:
        print(f"You can't afford {item}:, your running total is now {running_total}")
    

    Also receipt += names[i[0]] probably doesn't do what you expect (concatenating a list with a string... handled as list). Use append instead.