Question

In: Computer Science

Write a python program that keeps names and email addresses in a dictionary as key-value pairs....

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.

  • Make some comments to explain your work please.

Solutions

Expert Solution

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.


Related Solutions

*Python* 1.1) Create an empty dictionary called 'addresses'. The dictionary you just created will map names...
*Python* 1.1) Create an empty dictionary called 'addresses'. The dictionary you just created will map names to addresses. A person's name (stored as a string) will be the KEY and that person's address (stored as a string) will be the VALUE. 1.2) Insert into the dictionary 'addresses' the names and addresses of two (possibly imaginary) friends of yours. 1.3) Create a second empty dictionary called 'ages'. The dictionary you just created will map names to ages. A person's name (stored...
1.Suppose a dictionary Groceries maps items to quantities.     Write a python to print the names...
1.Suppose a dictionary Groceries maps items to quantities.     Write a python to print the names of the grocery items whose quantity exceeds 400.     For example, if groceries = {‘cake mixes’: 430, ‘cheese’:312, ‘Orange’:525, ‘candy bars’: 217}         The output will be                                 Cake mixes                                 Orange 2. which Python string method would be the best choice to print the number of time “the” occurs in a sentence entered by the user? Provide a one word answer. Just...
Write a program IN PYTHON of the JUPYTER NOOTBOOK that keeps getting a set of numbers...
Write a program IN PYTHON of the JUPYTER NOOTBOOK that keeps getting a set of numbers from user until the user enters "done". Then shows the count, total, and average of the entered numbers. This should the answer when finished Enter a number: 55 Enter a number: 90 Enter a number: 12 Enter a number: done You entered 3 numbers, total is 157, average is 52.33333
Write a program in python to read from a file the names and grades of a...
Write a program in python to read from a file the names and grades of a class of students to calculate the class average, the maximum, and the minimum grades. The program should then write the names and grades on a new file identifying the students who passed and the students who failed. The program should consist of the following functions: a) Develop a getGrades() function that reads data from a file and stores it and returns it as a...
Please write in Python code please Write a program that creates a dictionary containing course numbers...
Please write in Python code please Write a program that creates a dictionary containing course numbers and the room numbers of the rooms where the courses meet. The dictionary should have the following key-value pairs: Course Number (key) Room Number (value) CS101 3004 CS102 4501 CS103 6755 NT110 1244 CM241 1411 The program should also create a dictionary containing course numbers and the names of the instructors that teach each course. The dictionary should have the following key-value pairs: Course...
Using LIST and FUNCTION Write a program in Python that asks for the names of three...
Using LIST and FUNCTION Write a program in Python that asks for the names of three runners and the time it took each of them to finish a race. The program should display who came in first, second, and third place.
Write a program that uses Python List of strings to hold the five student names, a...
Write a program that uses Python List of strings to hold the five student names, a Python List of five characters to hold the five students’ letter grades, and a Python List of four floats to hold each student’s set of test scores. The program should allow the user to enter each student’s name and his or her four test scores. It should then calculate and display each student’s average test score and a letter grade based on the average....
I have a python dictionary with the following format Key Type Value January str ['January 01...
I have a python dictionary with the following format Key Type Value January str ['January 01 2020', 'January 02 2019', 'January 03 2018'] June str ['June 04 2018', 'June 05 2018', 'June 06 2016] August str ['Augsut 07 2016', 'August 08 2016'] How do return the following conclusion with python code? January has the most day (1) in 2020 January has the most day (1) in 2019 June has the most days (2) in 2018 August has the most days...
Using Python, write a program named hw3a.py that meets the following requirements: Create a dictionary called...
Using Python, write a program named hw3a.py that meets the following requirements: Create a dictionary called glossary. Have the glossary include a list of five (5) programing words you have learned in chapters 4-6. Use these words as keys to your dictionary. Find the definition of these words and use them as the values to the keys. Using a loop, print each word and its meaning as neatly formatted output. Create three dictionaries called person. Have each of the person...
Python Jupiter Notebook Write a program that keeps getting a set of numbers from user until...
Python Jupiter Notebook Write a program that keeps getting a set of numbers from user until the user enters "done". Then shows the count, total, and average of the entered numbers. Example: Enter a number: 55 Enter a number: 90 Enter a number: 12 Enter a number: done You entered 3 numbers, total is 157, average is 52.33333
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT