1

我在 python 中创建了一个字典作为我的第一个“主要”项目。我正在使用它来跟踪关键词。输入的只是示例,因此请随时改进我的定义(:

我是 python 新手,所以请随时批评我的技术,这样我就可以在它变得更糟之前学习!

我想知道的是,是否有一种方法可以处理字典中未包含的搜索。

如“抱歉,找不到您要查找的单词,您要尝试其他搜索吗?”

无论如何,这是我的代码:

Running = True

Guide = {
'PRINT': 'The function of the keyword print is to: Display the text / value of an object',

'MODULO': 'The function of Modulo is to divide by the given number and present the remainder.'
'\n The Modulo function uses the % symbol',

'DICTIONARY': 'The function of a Dictionary is to store a Key and its value'
'\n separated by a colon, within the {} brackets.'
'\n each item must be separated with a comma',

'FOR LOOP': 'The For Loop uses the format: \n '
            'For (variable) in (list_name): (Do this)',

'LINE BREAKS': ' \ n ',

'LOWERCASE': 'To put a string in lower case, use the keyword lower()',

'UPPERCASE': 'To put a string in upper case use the keyword upper()',

'ADD TO A LIST': 'To add items to a list, use the keyword: .append'
'\n in the format: list_name.append(item)',

'LENGTH': 'To get the length of a STRING, or list use the keyword len() in the format: len(string name)', }

while Running:
    Lookup = raw_input('What would you like to look up? Enter here: ')
    Lookup = Lookup.upper()
    print Guide[str(Lookup)]
    again = raw_input('Would you like to make another search? ')
    again = again.upper()
    if again != ('YES' or 'Y'):
        Running = False
    else:
        Running = True
4

3 回答 3

1

两种选择。

使用in运算符:

d = {}

d['foo'] = 'bar'

'foo' in d
Out[66]: True

'baz' in d
Out[67]: False

或者使用get字典的方法并提供可选的 default-to 参数。

d.get('foo','OMG AN ERROR')
Out[68]: 'bar'

d.get('baz','OMG AN ERROR')
Out[69]: 'OMG AN ERROR'
于 2013-10-12T16:44:34.147 回答
1

您可以使用try/except块:

try:
    # Notice that I got rid of str(Lookup)
    # raw_input always returns a string
    print Guide[Lookup]
# KeyErrors are generated when you try to access a key in a dict that doesn't exist
except KeyError:
    print 'Key not found.'

此外,为了使您的代码正常工作,您需要编写这行代码:

if again != ('YES' or 'Y'):

像这样:

if again not in ('YES', 'Y'):

这是因为,就目前而言,您的代码正在由 Python 评估,如下所示:

if (again != 'YES') or 'Y':

此外,由于True在 Python 中非空字符串的计算结果为,因此具有这样的代码将使 if 语句始终返回True,因为'Y'它是一个非空字符串。

最后,您可以完全摆脱这部分:

else:
    Running = True

因为它只是将一个变量分配给它已经相等的变量。

于 2013-10-12T16:45:33.970 回答
0

如果你更换,你可以得到你想要的

print Guide[str(Lookup)]

badword = 'Sorry, the word you were looking for could not be found, would you like to try another search?' 
print Guide.get(lookup,badword)

跳出来的一件事是用大写字母命名你的字典。通常为类保存大写字母。另一种有趣的事情是,这是我第一次看到真正用作字典的 dict。:)

于 2013-10-12T16:48:28.580 回答