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

时间:2014-09-24 05:49:13

标签: python python-3.x

所以我正在编写一个代码,用于在字典中搜索用户输入的密钥。为此,我将用户键入所需的键,将该键的定义附加到列表中,然后打印列表。

由于某些奇怪的原因,我的if serachT in dictionary行被忽略了。程序将跳转到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()

1 个答案:

答案 0 :(得分:0)

你应该首先填充你的字典,然后开始查找。幸运的是,在你的情况下,这是微不足道的:

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