In: Computer Science
Write a python program that keeps names and email addresses in a dictionary as key-value pairs. The program should display a menu that lets the user look up a person’s email address, add a new name and email address, change an existing email address, and delete an existing name and email address. The program should bind the dictionary and save it to a file when the user exits the program. Each time the program starts, it should retrieve the dictionary from the file and unbind it. The program should run continuously until the user selects option exit from the menu. You can also explore using Python pickle library.
def add_contact(): #Add Contact function.In order to add a contact
print("\nAdd Contact\n")
import pickle #Pickle module
try: #Tries to open binary file. Carries out commands for existing dict.
contact_file = open("Contacts.dat","rb") #Load binary
contact_set = pickle.load(contact_file) #Load dictionary
contact_file.close() #Securing file closure
contact = input("Enter contact name: ") #Contact name
email = input("Enter e-mail: ") #Contact e-mail
contact_set.update({contact : email})
contact_file = open("Contacts.dat","wb") #Load binary for update.
pickle.dump(contact_set,contact_file) #Updated binary.
contact_file.close() #Closure.
except: #if no binary file exists
print("You have no existing contacts!")
contact = input("Enter contact name: ")
email = input("Enter e-mail: ")
contact_set = {}
contact_set.update({contact : email})
contact_file = open("Contacts.dat","wb") #Writes updated dictionary
pickle.dump(contact_set,contact_file) #to binary file.
contact_file.close()
return
def check_list(): #Call it a 'background function'.Checks for existing file/dictionary.
import pickle
try:
contact_file = open("Contacts.dat","rb")
contact_set = pickle.load(contact_file)
contact_file.close()
if contact_set == {}: #if no dictionary exists
print("You have no contacts!")
add = input("Do you want to add a contact? ")
if 'yes' in add.lower():
add_contact() #Return to the contact_add function
else:
return
else:
return contact_set
except EOFError: #Response to empty binary or reading error.
print("You have no contacts!")
add = input("Do you want to add a contact? ")
if 'yes' in add.lower():
add_contact()
else:
return
except FileNotFoundError: #Response if no binary exists.
print("You have no contacts!")
add = input("Do you want to add a contact? ")
if 'yes' in add.lower():
add_contact()
else:
return
def search_contact(): #Function to search contacts.
print("\nSearch Contact\n")
import pickle
contact_set = check_list() #File/dictionary check
if contact_set == None: #Function break condition
return
else:
try:
search_name = input("Enter contact name, or 'All' ")
if search_name.lower() == 'all':
for key, value in sorted(contact_set.items()): #Attempts to
print("Name: ", key, "\nEmail:", \
value,"\n") #print a list of contact names and email
return
else:
print("Name: ", search_name, "\nEmail:", \
contact_set[search_name])
return
except KeyError: #Response for invalid entry.
print("Entry does not exist!")
show_list = input("Would you like to check your list? ")
if 'yes' in show_list.lower():
for key, value in sorted(contact_set.items()):
print("Name: ", key, "\nEmail:", \
value,"\n")
else:
return
def edit_contact(): #Function to edit contacts.
print("\nEdit Contact\n")
import pickle
contact_set = check_list() #Check
if contact_set == None:
return
else:
edit = input("Enter contact name ") #User-specified name
if edit not in contact_set: #for non-existing contact.
create = input("Contact not in list. Create new contact? ")
if 'yes' in create.lower():
new_email = input("Enter e-mail: ")
contact_set[edit] = new_email #creates new contact and email values.
print("Name: ", edit, "\nEmail:", \
contact_set[edit])
contact_file = open("Contacts.dat","wb")
pickle.dump(contact_set,contact_file) #Update binary.
contact_file.close()
return
else:
return
else: #for existing contact.
new_email = input("Enter new e-mail: ")
contact_set[edit] = new_email #Updates key with new value.
print("Name: ", edit, "\nNew Email:", \
contact_set[edit])
contact_file = open("Contacts.dat","wb")
pickle.dump(contact_set,contact_file)
contact_file.close()
return
def delete_contact(): #Function to delete contacts.
print("\nDelete Contact\n")
import pickle
contact_set = check_list() #Check
if contact_set == None:
return
else:
try:
delete = input("Enter contact name: ")
contact_set.pop(delete) #Deletion of key/value from dictionary.
print(delete,"has been deleted from your list.")
contact_file = open("Contacts.dat","wb")
pickle.dump(contact_set,contact_file) #Update binary
contact_file.close()
if contact_set == None: #Quick break from function.
print("No contacts found.")
else:
return
except KeyError: #In case of invalid input.
print("Entry does not exist!")
show_list = input("Do you want to to check your list? ")
if 'yes' in show_list.lower():
for key, value in sorted(contact_set.items()):
print("Name: ", key, "\nEmail:", \
value,"\n")
else:
return
def main_menu(): #Main Menu function
select = ""
while select.lower() != "quit": #until the value of select is not "quit",continue the program
print("\nMain Menu\n")
select = input("Choose an option (Number or Name):\n" #menu for the user
"1. Add Contact\n"
"2. Search Contact\n"
"3. Edit Contact\n"
"4. Delete Contact\n"
"5. Quit\n\n")
if select.lower() in "1. add contact": #if select is 1 or add contact
add_contact()
elif select.lower() in "2. search contact":#if select is 2 or search contact
search_contact()
elif select.lower() in "3. edit contact":#if select is 3 or edit contact
edit_contact()
elif select.lower() in "4. delete contact":#if select is 4 or delete contact
delete_contact()
elif select.lower() in "5. quit":
break
else:
print("Invalid input.")
main_menu()
Here's a preview of the output
Comment in case of any doubts.