r/learnpython • • 17h 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

9 comments sorted by

7

u/atarivcs 17h ago edited 17h 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.

1

u/Adbelhak_Unsicker 16h ago

right, the unpacking syntax in the for loop is spot on tbh.

1

u/supercoach 9h ago

I'd question what format the output is supposed to be in. Switching from list to dict seems like it's asking for double handling on the result.

Aside from that, the logic does work.

2

u/kilkil 7h ago

hmm, idk that code looks correct to me.

do you have a specific example of an input where your code is giving the wrong output? and if so, what is the expected vs actual output?

-9

u/delsystem32exe 17h 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.

5

u/Outside_Complaint755 16h 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?

2

u/Expensive-Bear-1376 16h ago

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