Python字典故障保护

时间:2013-10-12 16:39:01

标签: python

我在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

3 个答案:

答案 0 :(得分: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'

答案 1 :(得分: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':

此外,由于非空字符串在Python中评估为True,因此使用这样的代码将使if语句总是返回True,因为{{1} }是一个非空字符串。

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

'Y'

因为除了将变量分配给已经等于的变量之外什么都不做。

答案 2 :(得分: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)

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