How to Change Specific Dictionary Key Value in List of Dicts, and Update CSV entry?

Viewed 27

I am currently working on an inventory system that takes use of a csv file. My next task is to be able to edit specific entries of specific items.

My CSV file looks like this

CSV File

Here is my current and relevant code:

class CsvReader:
   def __init__(self): 
       self.result = []

   def make_dict_items(self):
       #fn = os.path.join('subdir', "Items2.csv")
       with open("Items2.csv") as fp:
           reader = csv.reader(fp)
           labels = next(reader, None)
           result = []
           for row in reader:
               if row:
                   row[0] = int(row[0])
                   row[1] = float(row[1])
                   row[2] = int(row[2])
                   pairs = zip(labels, row)
                   self.result.append(dict(pairs))

   def return_price(self, item):
       return self.result[item]["Price "]

   def add_item(self):
      item_num = int(input("What is the items #?\n"))
      price = float(input("What is the items price?\n"))
      quant = int(input("What is the items quantity?\n"))
      name = input("What is the items name?\n")
      new_row = [item_num, price, quant, name]
      with open("Items2.csv", "a+") as  fp:
          reader = csv.reader(fp)
          fp.seek(0)
          labels = next(reader, None)
          writer = csv.writer(fp)
          new_record = dict(zip(labels, new_row))
          self.result.append(new_record)
          writer.writerow(new_record.values())


  #method I am messing with/trying to implement
  def change_price(self):
       print(self.result)
       item_to_change = int(input("What item would you like to change the price of?\n"))
       print("The current price of " + return_name(item_to_change) " is " + 
       (return_price(item_to_change))
       price = float(input("What would you like to update the price to?\n"))
       self.result[item_to_change]["Price "] = price
       updated_row = []
       with open("Items2.csv", "a+") as  fp:
          reader = csv.reader(fp)
          fp.seek(0)
          labels = next(reader, None)
          writer = csv.writer(fp)
          new_record 

I am currently trying to implement a method that can edit the price of specific items in the list of dicts. For example, if I want to edit Blueberry Muffin, I want to be able to look at the current row of Blueberry Muffin, edit the price of it to some float, and append the specific dict key value, save it to the dict, and implement it in the main csv file and list of dicts.

In lamen terms, I see the Blueberry Muffin is 5.99, and want to be able to change it to 6.99, and implement it to my current csv and display it using the pre-existing methods I have

My last method in my CsvReader class is an attempt to try to implement this. How would I do so? I figure it would be fairly similar to the method I have which adds a new item?

0 Answers
Related