r/learnpython • • 1h ago

Help a beginner out with tuple unpacking :D

Yes I know its rather beginner, but since starting my python class I've been breezing through and its been so fun to learn, and I began to wonder why so many pythonists and other high level language users say its so hard.

Then I met tuple unpacking. I don't know what it is or why but its so hard for me to grasp and do. Here's an example problem I struggled with:

Q: analyze daily revenue based on the meals customers purchase

menu = {

"Burger": 12.50,

"Pizza": 15.00,

"Pasta": 13.50,

"Salad": 9.00,

"Sandwich": 8.50,

"Fries": 4.00

}

orders = [

("Monday", "Burger", 2), ---- These are Day, Product, Quantity btw

("Monday", "Pizza", 1),

("Tuesday", "Pasta", 3),

("Wednesday", "Burger", 1),

("Wednesday", "Fries", 4),

("Thursday", "Pizza", 2),

("Friday", "Sandwich", 2),

("Saturday", "Pasta", 2),

("Sunday", "Salad", 3)

]

Basically I'm supposed to get the price from the dictionary, and add to orders to get the daily revenue, such as like

Monday: 40.00
Tuesday: 40.5

and etc

But I keep messing up, I just can't seem to grasp the concept despite how much I have GPT give me more problems, the closest I got was this. One recurring issue I have is making sure a day doesn't repeat, like having Multiple Mondays when it should just be one monday and the final revenue for that day:

def calculate(sales):

daily_sales = {}

for day, product, quantity in orders:

price = menu[product]

daily_sales[day] = daily_sales.get(day, 0) + (price * quantity)

return(daily_sales)

print(orders)

0 Upvotes

4 comments sorted by

•

u/atarivcs 59m ago edited 49m ago

You're just printing the original "orders" list.

You need to actually call the "calculate" function, and print its result:

total = calculate(orders)
print(total)

Your problem doesn't seem to have anything to do with tuple unpacking.

-3

u/delsystem32exe 1h ago

yeah for this u will want to add that list of tuples to an sqlite database and then to get the sales you should use an sql query. that is the best way to go.

•

u/Outside_Complaint755 27m ago

This is an example problem from a class or textbook to show how to work with dictionaries and tuples. Why are you bringing up SQL databases when that has nothing to do with OP's question?

•

u/Expensive-Bear-1376 14m ago

What do you expect from a user with such a name?