2

I have created a dictionary in python as my first 'major' project. I'm using it to keep track of key words as I go along. The entered are just examples so feel free to improve my definitions (:

I'm new to python so feel free to criticise my technique so I can learn before it gets any worse!

What I'm wondering is, would there be a way to deal with searches that are not included in the dictionary.

As in 'Sorry, the word you were looking for could not be found, would you like to try another search?'

Anyway, here's my code:

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
user2874417
  • 151
  • 1
  • 11
  • 1
    Note that `again != ('YES' or 'Y')` is only ever going to work for `YES`; `('YES' or 'Y')` is going to evaluate to just `'YES'`. You want to use `if again in ('YES', 'Y'):` instead. – Martijn Pieters Oct 12 '13 at 16:46
  • In python, it is convention to only use capital letters for class names. For variables/functions do `variables_with_underscores`. Classes use `CamelCase`. See [PEP8](http://www.python.org/dev/peps/pep-0008/) for more style conventions. – SethMMorton Oct 12 '13 at 21:27

3 Answers3

2

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.

  • Thanks, Real help! I don't follow the logic of the "if again not in ('YES', 'Y')" Line though. If the value of again is not one of the two in brackets? – user2874417 Oct 12 '13 at 16:58
  • @user2874417 - That is a very common mistake among Python newbies--don't feel ashamed (I hit that too when I was learning ;). I explained better above. –  Oct 12 '13 at 17:04
  • While I'm here and have access to your expertise, is it possible to search a dictionary by both key and value? If I have an entry for example french: 'Blue': 'Bleu. Could I search for 'Bleu' instead of the key – user2874417 Oct 12 '13 at 17:13
  • @user2874417 - That is not exactly how a dictionary is supposed to work, but I guess you could do: `if 'Bleu' in dct.values():`, where `dct` is the dictionary. –  Oct 12 '13 at 17:23
1

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'
roippi
  • 25,533
  • 4
  • 48
  • 73
0

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. :)

James Robinson
  • 822
  • 6
  • 13