因此,这里是我的问题:用于搜索输入的Python搜索字典键
我想搜索字典以查看任何键是否包含用户输入的关键字。例如,用户搜索John。
elif option == 3:
count = 0
found = None
search_key = input("What do you want to search for? ").lower()
for key, val in telephone_directory.items(): #takes each element in telephone directory
if search_key in key: #checks if it contains search_key
if found is None:
found = val
count = 1
if found is not None:
print(" ")
print("More than one match found. Please be more specific.")
print(" ")
count = 2
break
if found is None:
print("Sorry, " + str(search_key) + " was not found.")
print(" ")
function_options() #redirects back
if found is not None and count < 2:
print(str(search_key) + " was found in the directory.")
print("Here is the file on " + str(search_key) + ":")
print(str(search_key) + ":" + " " + telephone_directory[search_key])
print(" ")
function_options() #redirects back
所以这就是我现在所处的位置。无论搜索结果如何,即使它是整个关键字,它都会返回“未找到”。我究竟做错了什么?
我想要对名称的一部分进行一些匹配,您应该期望可以有多个返回的情况。在这种情况下会发生什么? – Josay
我会添加一个案例,如果它带来超过2个,它会要求用户更具体。不是一个大问题。 – Aristides