Python 如何在字典中显示多个项目?
我有一个程序,它有一个搜索选项,如果鸡肉或鸡肉在库存中,它只需输入chi(不区分大小写)即可调出物品。问题是如何使函数返回包含chi的所有项 例如,如果我有鸡、鸡、鸡和鸡的存货,我应该能够输入chi,它应该打印出每个项目的所有信息 受影响的代码(非完整程序): 我该如何解决这个问题 用于测试的完整程序代码:Python 如何在字典中显示多个项目?,python,Python,我有一个程序,它有一个搜索选项,如果鸡肉或鸡肉在库存中,它只需输入chi(不区分大小写)即可调出物品。问题是如何使函数返回包含chi的所有项 例如,如果我有鸡、鸡、鸡和鸡的存货,我应该能够输入chi,它应该打印出每个项目的所有信息 受影响的代码(非完整程序): 我该如何解决这个问题 用于测试的完整程序代码: import os import json class Inventory: def __init__(self): #AT LAUNCH GROUPS AND L
import os
import json
class Inventory:
def __init__(self):
#AT LAUNCH GROUPS AND LOADING FUNCTION
self.items = {}
self.load()
def remove(self, ID):
#REMOVING ITEMS FOR LISTS AND OUTPUT DOCUMENT
del self.items[str(ID)]
self.save()
def add(self, ID, name, qty):
#ADDING ITEMS FOR LISTS AND OUTPUT DOCUMENT
self.items[str(ID)] = {"name": name, "qty": qty}
self.save()
def update(self, ID, update):
#UPDATING ITEMS FOR LISTS AND OUTPUT DOCUMENT
self.items[str(ID)]["qty"] += update
self.save()
def search(self, query):
#SEARCHING DATA BASED ON CLOSEST CHARACTER MATCH - NOT CASE SENSITIVE
output = []
for id in self.items:
if str(query) == id or self.items[id]['name'].lower().startswith(str(query).lower()):
output.append((id, self.items[id]['name'], self.items[id]['qty']))
if output: return output
else: return None
def __str__(self):
#FORMATTING
out = ""
for id, d in self.items.items():
out += f"ID Number : {id} \nItem Name : {d['name']}\nQuantity : {d['qty']}\n"
out += "----------\n"
return out
def save(self):
#WHERE TO SAVE TO
with open('data.txt','w') as outfile:
json.dump(self.items, outfile)
def load(self):
#WHERE TO PUT DATA FROM WHEN RELAUNCHING PROGRAM
try:
with open('data.txt','r') as json_file:
self.items = json.load(json_file)
except:
print("Can't load old inventory, starting fresh")
self.items = {}
def menuDisplay():
#MENU FOR PROGRAM
"""Display the menu"""
print('=============================')
print('= Inventory Management Menu =')
print('=============================')
print('(1) Add New Item to Inventory')
print('(2) Remove Item from Inventory')
print('(3) Update Inventory')
print('(4) Search Item in Inventory')
print('(5) Print Inventory Report')
print('(99) Quit')
def add_one_item(inventory):
#ADDING PROMPT AND ERROR CHECKING
print('Adding Inventory')
print('================')
while True:
try:
new_ID = int(input("Enter an ID number for the item: "))
if inventory.search(new_ID):
print("ID number is taken, please enter a different ID number")
continue
new_name = input('Enter the name of the item: ')
new_qty = int(input("Enter the quantity of the item: "))
inventory.add(new_ID, new_name, new_qty)
break
except Exception as e:
print("Invalid choice! try again! " + str(e))
print()
def remove_one_item(inventory):
#REMOVING PROMPT AND ERROR CHECKING
print('Removing Inventory')
print('==================')
while True:
try:
removing = int(input("Enter the item's ID number to remove from inventory: "))
if inventory.search(removing):
inventory.remove(removing)
else:
print("Item not in inventory")
continue
break
except Exception as e:
print("Invalid choice! try again! " + str(e))
print()
def ask_exit_or_continue():
#OPTION TO CONTINUE OR QUITE PROGRAM
return int(input('Enter 98 to continue or 99 to exit: '))
def update_inventory(inventory):
#UPDATING PROMPT AND ERROR CHECKING
print('Updating Inventory')
print('==================')
while True:
try:
ID = int(input("Enter the item's ID number to update: "))
if inventory.search(ID):
update = int(input("Enter the updated quantity. Enter 5 for additional or -5 for less: "))
inventory.update(ID, update)
else:
print("ID number is not in the system, please enter a different ID number")
continue
break
except Exception as e:
print("Invalid choice! try again! " + str(e))
print()
def search_inventory(inventory):
#SEARCHING PROMPT AND ERROR CHECKING
print('Searching Inventory')
print('===================')
while True:
try:
search = input("Enter the name of the item: ")
result = inventory.search(search)
if result is None:
print("Item not in inventory")
continue
else:
for found in result:
ID, name, qty = found
print('ID Number: ', ID)
print('Item: ', name)
print('Quantity: ', qty)
print('----------')
break
except Exception as e:
print("Invalid choice! try again! " + str(e))
print()
def print_inventory(inventory):
#PRINT CURRENT LIST OF ITEMS IN INVENTORY
print('Current Inventory')
print('=================')
print(inventory)
def main():
#PROGRAM RUNNING COMMAND AND ERROR CHECKING
inventory = Inventory()
while True:
try:
menuDisplay()
CHOICE = int(input("Enter choice: "))
if CHOICE in [1, 2, 3, 4, 5]:
if CHOICE == 1:
add_one_item(inventory)
elif CHOICE == 2:
remove_one_item(inventory)
elif CHOICE == 3:
update_inventory(inventory)
elif CHOICE == 4:
search_inventory(inventory)
elif CHOICE == 5:
print_inventory(inventory)
exit_choice = ask_exit_or_continue()
if exit_choice == 99:
exit()
elif CHOICE == 99:
exit()
except Exception as e:
print("Invalid choice! try again!"+str(e))
print()
# If the user pick an invalid choice,
# the program will come to here and
# then loop back.
main()
代码返回第一个匹配项。此搜索返回所有匹配项
def search(self, query):
""" Search items for all matching id's in query.
"""
output = [id for id in self.items if str(query).upper() in id.upper()]
return output if output != [] else None
作为一个独立的演示,我构建了一个包含3个项目的数据库和一个搜索方法的类
对于搜索方法,我在列表中使用id.upper()中的if str(query).upper()
Db类:
定义初始化(自):
self.items={
'Picture1':{'name':'name1','qty':1},
'Picture2':{'name':'name2','qty':2},
'Picture3':{'name':'name3','qty':3}
def搜索(自我,查询):
return[(id,self.items[id]['name'],self.items[id]['qty'])
如果id.upper()中的str(query.upper()),则表示self.items中的id
db=db()
db.search('pic')
db.search('ure2')
如果你觉得这个问题无法解释,也许我答错了。您应该尝试更好地解释。您能更新您的答案以使用我提供的程序代码吗?答案已更新。第一个代码块可以复制并粘贴到您的代码中。您的错误是在尚未获取所有信息时使用return。请查看我的帖子以获得进一步的解释。我认为这是正确的,但我一直得到一个关于if输出的无效语法:@GeorgeDavidson请向我显示错误消息,并将id变量更改为其他内容,因为它是if输出中的内置函数名:“:”突出显示橙色。没有特殊的错误消息。@GeorgeDavidson我已经编辑了这篇文章,不要复制并粘贴到你的py文件中,因为缩进,请重写它。上面写着“:”仍然突出显示橙色
def search(self, query):
""" Search items for all matching id's in query.
"""
output = [id for id in self.items if str(query).upper() in id.upper()]
return output if output != [] else None
def search(self, query):
#SEARCHING DATA BASED ON CLOSEST CHARACTER MATCH - NOT CASE SENSITIVE
output = []
for id in self.items:
if str(query) == id or self.items[id]['name'].lower().startswith(str(query).lower()):
output.append((id, self.items[id]['name'], self.items[id]['qty']))
if output:
return output
else:
return None