【发布时间】:2021-03-07 08:18:10
【问题描述】:
因此,如果使用 userInput 在字典中找到键,我的代码会输出值。如果在字典的键中找不到 userInput,我想打印一条消息“疾病名称不存在”。我可以让它工作,但是,它会遍历整个列表并为 text.txt 的每一行重复“疾病不存在”
我不知道如何让它只打印一次。这是我的代码:
# Complete this function to meet its specifications.
# Begin with an empty dictionary, fill it, and return it.
def disease_to_code_dictionary( ) :
""" Function returns a dictionary with disease names as keys and
ICD 10 codes as values. """
diseases = {}
infile = open("ICD10.txt","r")
header_row = infile.readline() # skip the header row
for line in infile :
cells = line.split("\t") # split by the tab character
if len(cells) >= 2 : # only if the line had a tab
code = cells[0]
disease = cells[1]
disease = disease.lower() # lowercase
disease = disease.replace("\"","") # remove all double quotes
diseases[disease] = code
infile.close()
return diseases
# Complete this function to meet its specifications.
# The program should give the code if the disease name exists
# otherwise say "Disease name does not exist.".
def query_disease_to_code() :
""" Interactive function to query code from disease name. """
d = disease_to_code_dictionary() # disease to code dictionary
query = input("Give disease name (q to quit): ")
while query != "q" :
query = query.lower() # lowercase
# complete here
for key, value in d.items():
if query in key:
print(value)
else:
print("Disease name does not exist.")
query = input("Give disease name (q to quit): ")
query_disease_to_code()
【问题讨论】:
-
您的打印语句在您的循环中,每个循环将打印一次。
-
哎呀等一下,我需要修复我的代码。我没有包含“疾病名称不存在”
-
我不确定你为什么要循环,如果你有一种疾病要检查,为什么不直接使用
in? -
它是一个完整的疾病列表。因为第一个函数是通过我桌面上的一个文件,该文件有一个代码和疾病名称列表
-
只需要检查查询是否与字典中的键匹配,如果匹配则吐出值
标签: python python-3.x dictionary for-loop if-statement