So I am looking for a way to add separate items to a list in the form of individual dictionaries that contain the grocery item's name, price, and quantity. I only started programming a few weeks ago so please forgive my horrendous code and beginner mistakes.
grocery_item = dict()
current_item = dict()
grocery_history = []
choice = 0
stop = True
while stop == True:
current_item['name'] = str(input('Item name: '))
current_item['quantity'] = int(input('Amount purchased: '))
current_item['cost'] = float(input('Price per item: '))
grocery_history.append(current_item)
choice = str(input('Press c to continue or q to quit'))
if choice == 'c':
stop = True
else:
stop = False
print(grocery_history)
When I input the information of two items (ie spam and eggs) I get the following output:
[{'name': 'Eggs', 'quantity': 12, 'cost': 1.5}, {'name': 'Eggs', 'quantity':
12, 'cost': 1.5}]
Instead of creating two different items the output just repeats the most recent one I entered. I am making some basic semantic error and I can't figure out how to populate the "grocery_history" list with different items from the user input loop. I tried using pythontutor.com for help but was just berated for being stupid. Any help is appreciated.
Try doing this:
grocery_item = dict()
grocery_history = []
choice = 0
stop = True
while stop == True:
current_item = dict()
current_item['name'] = str(input('Item name: '))
current_item['quantity'] = int(input('Amount purchased: '))
current_item['cost'] = float(input('Price per item: '))
grocery_history.append(current_item)
choice = str(input('Press c to continue or q to quit'))
if choice == 'c':
stop = True
else:
stop = False
print(grocery_history)
By creating a new dictionary in each loop you'll avoid the duplicate error that you're seeing.