Python 为什么我的if-else语句被忽略

Python 为什么我的if-else语句被忽略,python,python-3.x,Python,Python 3.x,因此,我正在编写一个代码,在字典中搜索用户输入的密钥。为此,我让用户输入他们想要的键,将该键的定义附加到列表中,然后打印列表 出于某种奇怪的原因,字典行中的if serachT被忽略了。程序将跳转到else,完全跳过if。我已删除else以验证if是否有效。关于为什么添加else忽略if有什么想法吗 import csv def createDictionary(): dictionary = {} found = [] searchT = input("What ar

因此,我正在编写一个代码,在字典中搜索用户输入的密钥。为此,我让用户输入他们想要的键,将该键的定义附加到列表中,然后打印列表

出于某种奇怪的原因,字典行中的if serachT被忽略了。程序将跳转到else,完全跳过if。我已删除else以验证if是否有效。关于为什么添加else忽略if有什么想法吗

import csv

def createDictionary():
    dictionary = {}
    found = []
    searchT = input("What are you seraching for ") 
    fo = open("textToEnglish2014.csv","r")
    reader = csv.reader(fo)
    for row in reader:
        dictionary[row[0]] = row[1]
        if searchT in dictionary:
            found.append(dictionary[row[0]])
            print(found)
        elif searchT not in dictionary:
            i = 0
            #print("NF")
            #exit()
    print(found)
    return found

createDictionary()

你应该先填充字典,然后开始查找。幸运的是,这在您的案例中并不重要:

def create_dictionary():
    with open("textToEnglish2014.csv", newline="") as fo:  # note the newline parameter!
        reader = csv.reader(fo)
        return dict(reader)
请注意,与以前不同,现在您的函数名有意义了

现在,您可以轻松地进行查找:

>>> dictionary = create_dictionary()
>>> searchT = input("What are you searching for? ")
What are you searching for? hello
>>> dictionary.get(searchT)   # returns None if searchT is not in dictionary
goodbye

我刚刚编辑了您的代码以改进格式,但我不能完全确定缩进是否正确。请仔细检查上面的代码是否与您实际运行的代码相匹配,特别是您所询问的if和else行的缩进。这与您的问题无关,但与那条长长的elif语句不同,一个简单的else:就足够了。您的代码对我来说就可以了。检查@TimPietzcker的答案是否有其他问题,但使用正确的搜索词,它可以运行if子句。