Post a cursory read of this I implemented a simple dictionary and an interface to assign, replace, look up, and redefine its terms to apply the concepts.
It's simple, but I'd still like to know any way I could make this cleaner and more pythonic.
def print_dict(dictionary):
for key in dictionary:
print("{} : {}".format(key, dictionary[key]))
def display_menu():
print("\n0 = Quit"
+ "\n1 = Look up a term"
+ "\n2 = Add a term"
+ "\n3 = Redefine a term"
+ "\n4 = Delete a term"
+ "\n5 = Display Dictionary"
)
def is_integer(value):
try:
temp = int(value)
return True
except ValueError:
return False
def validate(choice):
if is_integer(choice) and 0 <= int(choice) <= 5:
return int(choice)
else:
print("Input must be an integer between 0 and 5, inclusive")
return validate(input("\nEnter Selection: "))
def lookup_term(dictionary):
term = input("which term would you like to look up? ")
if term in dictionary:
print("{} : {}".format(term, dictionary.get(term)))
else:
print("Term does not exist, input 2 to add new term")
def redefine_term(dictionary):
term = input("which term would you like to redefine? ")
if term in dictionary:
dictionary[term] = input("and its definition? ")
else:
print("Term does not exist, input 2 to add new term")
def add_term(dictionary):
term = input("What term would you like to add? ")
if term in dictionary:
print("Already exists. To redfine input 3")
else:
dictionary[term] = input("and its definition? ")
def delete_term(dictionary):
del dictionary[input('Which term would you like to delete? ')]
def process_request(choice, dictionary):
if choice == 0:
print("Thank you for using Stack Exchange Site Abbreviation!")
quit()
elif choice == 1:
lookup_term(dictionary)
elif choice == 2:
add_term(dictionary)
elif choice == 3:
redefine_term(dictionary)
elif choice == 4:
delete_term(dictionary)
else:
print_dict(dictionary)
def main():
site_dictionary = {
'SO' : 'Stack Overflow',
'CR' : 'Code Review',
'LH' : 'Lifehacks',
'??' : 'Puzzling',
'SR' : 'Software Recommendations',
'SU' : 'Super User',
'M' : 'Music: Practice & Theory',
'RE' : 'Reverse Engineering',
'RPi' : 'Raspberry Pi',
'Ro' : 'Robotics'
}
print_dict(site_dictionary)
print("\nWelcome to Stack Exchange Site Abbreviation Translator!")
display_menu()
while(True):
process_request(validate((input("\nEnter Selection: "))), site_dictionary)
if __name__ == "__main__":
main()