0

I have items in a csv file that I have imported, opened and stored in an enumerated list. The next task is to ask the user to select a grocery item, select the quantity and loop back to keep adding items until the user enters 0.

I am just unsure what to do next. Can someone give me hint a please?

import csv

with open ('groceries.csv') as csv_file:
    reader = csv.reader(csv_file)

    mydict = {rows[0]:rows[1]for rows in reader}
    print(mydict)

    enumeratemydict = enumerate(mydict)
    for item in  enumerate(mydict):
        print(item)

The output

{'item': 'price', 'water': '2.35', 'bread': '1.12', 'chicken': '2.56', 'rice': '0.95', 
 'soda': '4.3', 'ice cream': '3.15', 'juice': '3.15', 'steak': '5.72', 
 'green beans': '0.48', 'cereal': '4.13'}

(0, 'item')
(1, 'water')
(2, 'bread')
(3, 'chicken')
(4, 'rice')
(5, 'soda')
(6, 'ice cream')
(7, 'juice')
(8, 'steak')
(9, 'green beans')
(10, 'cereal')
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • Have a look at `while` loop and `input` function :-) – Léopold Houdin Sep 28 '18 at 20:44
  • essentially you should apply something like this: [Ask user for input until valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) - the answers handle validating user input and looping- you would do smth similar – Patrick Artner Sep 28 '18 at 20:45

1 Answers1

0

Hope this helps, tried to comment everything clearly! Like mentioned in the comments, you'll need to use a while loop, the "input" function to get the user input, and lists.

import csv

with open ('groceries.csv') as csv_file:
    reader = csv.reader(csv_file)

    mydict = {rows[0]:rows[1]for rows in reader}
    print(mydict)

    enumeratemydict = enumerate(mydict)
    for item in  enumerate(mydict):
        print(item)
    # Create an empty list of everything that the user wants that we will add to later
    purchased_items = []
    # Ask user to select an item
    user_answer = ""
    while True:
        user_answer = input("Enter the number corresponding to your item: ") # Get user input
        if user_answer != '0': # If user entered 0 
            break # Leave the while loop, thus ending the program
        item_num = int(user_answer) # Convert to integer
        selected_item = mydict[item_num] # Figure out what item that integer corresponds to in your dict

        quantity = input("Enter the quantity: ") # Get user input
        quantity = int(quantity) # Convert to integer
        purchased_items.append([selected_item, quantity]) # add a list containing the item and quantity to your list of purchased items.

        print(purchased_items) # See what the user has bought up to this point
Erik
  • 1,196
  • 2
  • 9
  • 18