import json
dictionary = {}
f = open("Dictionary.txt", "w")
if f.readline() == "" :
f.write("{}")
f.close();
exitLoop = False
while exitLoop == False :
dictionary = json.loads(open("Dictionary.txt").read())
print("Welcome to the dictionary.")
print("To begin, type your option.")
print("a) Search for a word")
print("b) Enter a word")
print("c) Display all words")
answer = raw_input()
if answer.lower() in ['a', 'a)'] :
word = raw_input("What word would you like to search for? ")
if word in dictionary :
print(word.capitalize()+" - "+dictionary[word].capitalize())
else :
print("Word not found!")
elif answer.lower() in ['b', 'b)'] :
word = raw_input("Enter a word: ")
definition = raw_input("Enter the definition: ")
word2 = word.lower();
definition2 = definition.lower();
dictionary[word2] = definition2
json.dump(dictionary, open("Dictionary.txt", "w"))
elif answer.lower() in ['c', 'c)'] :
for k, v in dictionary.iteritems():
print (k.capitalize()+" - "+v.capitalize())
print("Would you like to quit? Y/N")
wantToQuit = raw_input();
if wantToQuit == "y" or wantToQuit == "Y" :
exitLoop = True
else :
exitLoop = False
EDIT: Made it so you don't have to create a file called Dictionary containing {}.
EDIT2: Cleaned up code.
Last edited by lotios611 on Sat Dec 05, 2009 8:34 am, edited 1 time in total.
By calling lower() on the variable answer and then using indexing to specify the first char in the string, you safeguard yourself against the user having the caps-lock on and/or them adding on an unnecessary bracket.
By calling lower() on the variable answer and then using indexing to specify the first char in the string, you safeguard yourself against the user having the caps-lock on and/or them adding on an unnecessary bracket.
Depending on the situation this could be a bad thing. If you have a "critical" decision, and the user enters "yes", changes his mind and only erases "es", then gets "yno". So if you're checking for "y" ...
Another alternative: