如何修改字典列表中指定Item #对应字典的键值?
问题解答
思路正确性
你的整体思路是可行的,但现有代码存在语法错误和逻辑问题:比如修改Price的方式错误(Price是数值类型而非列表,不能用append和pop)、缩进错误、拼写错误(databse应为database),以及未处理Item#不存在的情况,需要调整修正。
获取匹配字典索引的方法
直接用enumerate()函数遍历列表,它会同时返回元素的索引和对应字典,找到匹配项时就能直接拿到索引:
def edit_item_interaction(self): self.database.show_available() edit_specific_item = self.enter_data("Enter the item # of the item you would like edit\n", int) target_index = None # 用enumerate同时获取索引和字典元素 for index, item in enumerate(self.database.result): if item["Item #"] == edit_specific_item: target_index = index break # 处理Item#不存在的情况 if target_index is None: print("Item not found!") return # 修改Price(直接赋值替换,无需列表操作) new_price = self.enter_data("Enter the new price\n", float) self.database.result[target_index]["Price "] = new_price # 修改Quantity new_quantity = self.enter_data("Enter the new quantity\n", int) self.database.result[target_index]["Quantity"] = new_quantity # 修改Name(字符串无需类型转换) new_name = input("Enter the new name\n") self.database.result[target_index]["Name"] = new_name
关键修正说明
- 索引获取:
enumerate()是最直接的方式,遍历过程中同时拿到索引和对应字典,无需额外计算。 - 错误处理:增加Item#不存在的判断,避免后续代码因
target_index为None报错。 - Price修改逻辑:字典里的
Price对应的值是float类型,直接赋值新值即可,原代码中用列表的append/pop是错误的。 - 语法修正:修正拼写错误、无效
break语句,以及float(change_price=...)的错误语法。 - 交互优化:可以扩展让用户选择具体要修改的字段(比如输入"Price"、"Quantity"或"Name"),而非强制修改所有字段,提升灵活性。
内容的提问来源于stack exchange,提问作者py_coder1019
相关产品推荐
相关产品推荐

