Reputation: 37
I'm writing a script for a grocery list for my course on Python. Everything looks good, except every time I append my list with a new dictionary entry, I overwrite the old values. I found a lot of similar questions on here already, but I hate to admit that I didn't quite understand a lot of the answers yet. Hopefully I can understand it a little better if I ask the question myself and know the context. Here is my code:
grocery_item = {}
grocery_history = []
stop = 'c'
while stop == 'c':
item_name = input('Item name:\n')
quantity = input('Quantity purchased:\n')
cost = input('Price per item:\n')
grocery_item = {'name':item_name, 'number': int(quantity), 'price':
float(cost)}
grocery_history.append(grocery_item) <<< # OVERWRITES OLD VALUES.
stop = input("Would you like to enter another item?\nType 'c' for
continue
or 'q' to quit:\n")
grand_total = 0
for items in range(0,len(grocery_history)):
item_total = grocery_item['number'] * grocery_item['price']
grand_total = grand_total + item_total
print(str(grocery_item['number']) + ' ' + str(grocery_item['name']) + '
' + '@' + ' ' + '$' + str(grocery_item['price']) + ' ' + 'ea' + ' ' +
'$' +
str(item_total))
item_total == 0
print('Grand total:$' + str(grand_total))
So instead of each input being saved and totaled up, it just overwrites all the previous inputs with the value of the last input entered and adds that up however many times it iterated through the loop. I understand why it overwrites the previous values and it makes perfect sense. I just don't know how to update the list while still outputting the original inputs. Thanks in advance for any help!
Upvotes: 2
Views: 1376
Reputation: 4537
The problem isn't where you think it is. The values are being appended correctly to grocery_history
. You can check that yourself with print(grocery_history)
.
The problem is in your for
loop. You're reading from grocery_item
(ie. the last item entered by the user) instead of from the whole grocery_history
list. Replace your for
loop with this one:
for i in range(0,len(grocery_history)):
item_total = grocery_history[i]['number'] * grocery_history[i]['price']
grand_total = grand_total + item_total
print(str(grocery_history[i]['number']) + ' ' + str(grocery_history[i]['number']) + ' ' + '@' + ' ' + '$' + str(grocery_history[i]['number']) + ' ' + 'ea' + ' ' + '$' + str(item_total))
item_total == 0
print('Grand total:$' + str(grand_total))
Upvotes: 0
Reputation: 39788
You create several dict
objects and assign each to grocery_item
. Each replaces the last under that name, which is fine because you also append
each to grocery_history
. However, you never use that list
(except to determine how many iterations of the totaling loop to perform); instead, you use grocery_item
again, which still has whatever single value you assigned to it last.
Just replace
for items in range(0,len(grocery_history)):
with
for grocery_item in grocery_history:
(You weren’t ever using items
anyway.)
Upvotes: 3