如何修改字典列表中指定字典的键值并更新CSV条目?
问题描述
我正在开发一个基于CSV文件的库存系统,下一步需要实现修改特定商品指定条目的功能。CSV文件结构包含商品编号、价格、数量、名称字段。当前已实现部分代码,正尝试完成change_price方法,用于修改字典列表中特定商品的价格(例如将蓝莓松饼的价格从5.99改为6.99),同时更新内存中的字典列表和主CSV文件。目前该方法尚未完成,请问该如何实现?是否与现有的add_item方法类似?
当前相关代码如下:
import csv 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
解决方案
和add_item方法不一样,add_item是追加新行到CSV,而修改操作需要重写整个CSV文件(因为要修改已有行)。具体实现步骤如下:
- 补充依赖方法:先实现
return_name方法,用于获取商品名称,和return_price逻辑一致:
def return_name(self, item): return self.result[item]["Name"] # 需对应你CSV实际的名称字段名,比如"Item Name"
修正语法错误:原代码中
print语句缺少运算符、括号,调用类方法需加self.前缀。更新内存数据:直接修改
self.result中对应索引的商品价格。重写CSV文件:以写入模式打开CSV,先写入表头,再将
self.result中的所有字典转换成列表行写入,覆盖原有内容。
修改后的完整change_price方法如下:
def change_price(self): # 检查内存是否已加载数据 if not self.result: print("No items loaded. Call make_dict_items() first.") return print(self.result) try: item_to_change = int(input("What item index would you like to change the price of?\n")) # 校验索引有效性 if item_to_change < 0 or item_to_change >= len(self.result): print("Invalid item index!") return # 获取当前商品信息并展示 current_name = self.return_name(item_to_change) current_price = self.return_price(item_to_change) print(f"The current price of {current_name} is {current_price}") # 读取新价格并更新内存 new_price = float(input("What would you like to update the price to?\n")) self.result[item_to_change]["Price "] = new_price # 重写整个CSV文件 with open("Items2.csv", "w", newline='') as fp: # 从第一个字典提取表头 labels = self.result[0].keys() writer = csv.writer(fp) writer.writerow(labels) # 写入表头 # 写入所有商品数据 for item in self.result: writer.writerow(item.values()) print("Price updated successfully!") except ValueError: print("Invalid input. Please enter a valid number.")
关键说明
- 增加了索引越界和输入错误的处理,避免程序崩溃。
- 重写CSV时使用
w模式,确保内存中的最新数据覆盖原有文件内容。 - 若CSV表头名称与代码中不一致(比如
Price后无空格),需同步修改字典的键名。
内容的提问来源于stack exchange,提问作者py_coder1019
相关产品推荐
相关产品推荐

