Python dictionary failsafe
This question already has an answer here:
You can use a try/except block:
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.'
Also, in order for your code to work, you need to make this line of code:
if again != ('YES' or 'Y'):
like this:
if again not in ('YES', 'Y'):
This is because, as it currently stands, your code is being evaluated by Python like so:
if (again != 'YES') or 'Y':
Furthermore, since non-empty strings evaluate to True
in Python, having the code like this will make the if-statement always return True
because 'Y'
is a non-empty string.
Finally, you can completely get rid of this part:
else:
Running = True
since it does nothing but assign a variable to what it already equals.
Two options.
Use the in
operator:
d = {}
d['foo'] = 'bar'
'foo' in d
Out[66]: True
'baz' in d
Out[67]: False
Or use the get
method of your dictionary and supply the optional default-to argument.
d.get('foo','OMG AN ERROR')
Out[68]: 'bar'
d.get('baz','OMG AN ERROR')
Out[69]: 'OMG AN ERROR'
You can get what you want if you replace
print Guide[str(Lookup)]
with
badword = 'Sorry, the word you were looking for could not be found, would you like to try another search?'
print Guide.get(lookup,badword)
One thing that jumped out is naming your dict with a capital letter. Generally capital letters are saved for classes. Another kind of funny thing is that this is the first time I've seen a dict actually used as a dictionary. :)
链接地址: http://www.djcxy.com/p/28888.html上一篇: python2代码在使用python3.5时会出错
下一篇: Python字典故障安全