Question

In: Computer Science

Complete the PA7_incomplete.py program (posted below) for an infinite interactive loop to process a dictionary. The...

Complete the PA7_incomplete.py program (posted below) for an infinite interactive loop to process a dictionary. The program starts by asking an input file name where the dictionary entries are stored. This file will be assumed be present and to contain two items in each line as key and value pairs separated by a comma, like the example.txt file (posted below). The file could be possibly empty. The program reads the contents of this file into a dictionary, closes the file and presents user with the following menu choices in an infinite loop: Add an entry Show value for a key Delete an entry Save the file Print the current dictionary Quit Complete rest of the program to process the dictionary interactively with the user. The following appropriate actions should be taken for each one of them and then the menu should be shown again unless the user quits. Add an entry: Ask the user for the key and value, and make an entry, if the key already exists then prompt the user whether to overwrite its value. Show value for a key: Ask the user for the key and show the corresponding value, point out if the key does not exist.


def main():
d = {} # dictionary

# Read the file's contents in the dictionary d
filename = input("Give the file name: ")
file = open(filename,"r")
for line in file:
# read key and value
key, value = line.split(",")
# remove whitespaces before and after
key = key.lstrip()
key = key.rstrip()
value = value.lstrip()
value = value.rstrip()
# insert entry in the dictionary
d[key] = value
file.close()

loop=True # continue looping if true

while (loop):
print("\n\nEnter one of the following menu choices:")
print("1 Add an entry")
print("2 Show value for a key")
print("3 Delete an entry")
print("4 Save the file")
print("5 Print the current dictionary")
print("6 Quit")
choice = input("Choice 1-6: ")
print("\n\n")

if (choice=="1"): # Add an entry
k = input("Give the key: ")
v = input("Give its value: ")
# complete the rest
elif (choice=="2"): # Show value for a key
k = input("Give the key: ")
# complete the rest
elif (choice=="3"): # Delete an entry
k = input("Give the key to delete the entry: ")
# complete the rest
elif (choice=="4"): # Save the file
print("Saving the file")
# complete the rest
elif (choice=="5"): # Print the current dictionary
l = list(d.keys()) # get all the keys
l.sort() # sort them
# complete the rest
elif (choice=="6"): # Quit
loop=False
# complete the rest
else :
print("Incorrect choice")

Delete an entry: Ask the user for the key and delete the entry, point out if the key does not exist Save the file: Save to the same file name in the same comma-separated format (do not worry about the order of entries), make sure to close the file Print the current dictionary: show value entries of the current dictionary on the screen (in alphabetical order of the keys). End the program. If the dictionary has been modified since the last save, then prompt the user whether it should be saved before quitting.

Solutions

Expert Solution

CODE -

def main():

    d = {} # dictionary

    # Read the file's contents in the dictionary d

    filename = input("Give the file name: ")

    file = open(filename,"r")

    for line in file:

        # read key and value

        key, value = line.split(",")

        # remove whitespaces before and after

        key = key.lstrip()

        key = key.rstrip()

        value = value.lstrip()

        value = value.rstrip()

        # insert entry in the dictionary

        d[key] = value

    file.close()

    loop=True # continue looping if true

    modified = False

    while (loop):

        print("\n\nEnter one of the following menu choices:")

        print("1 Add an entry")

        print("2 Show value for a key")

        print("3 Delete an entry")

        print("4 Save the file")

        print("5 Print the current dictionary")

        print("6 Quit")

        choice = input("Choice 1-6: ")

        print("\n\n")

        if (choice=="1"): # Add an entry

            k = input("Give the key: ")

            v = input("Give its value: ")

            d[k] = v                        # Adding the entry to the dictionary

            modified = True                 # Setting modified to true which indicates that dictionary has been modified after saving the file.

        elif (choice=="2"): # Show value for a key

            k = input("Give the key: ")

            if k in d:

                print("Key:", k, "\nValue:", d[k])          # Displaying the key and value if key is found in the dictionary

            else:

                print("Key not found!")                     # Displaying message that key not found if key is not present in the dictionary

        elif (choice=="3"): # Delete an entry

            k = input("Give the key to delete the entry: ")

            if k in d:

                del d[k]                    # Deleting the entry if key is found in the dictionary

                modified = True             # Setting modified to true which indicates that dictionary has been modified after saving the file.

                print("Entry Deleted.")

            else:

                print("Key not present!")   # Displaying message that key not present if key is not found in the dictionary

        elif (choice=="4"): # Save the file

            print("Saving the file")

            file = open(filename,"w")       # Opening the file for writing

            for k in d:

                file.write(k + ", " + d[k] + "\n")  # Writing the key and value to the file seperated by comma

            modified = False                # Setting modified to false which indicates that dictionary has not been modified after saving the file.

            file.close()                    # Closing the file

        elif (choice=="5"): # Print the current dictionary

            l = list(d.keys()) # get all the keys

            l.sort() # sort them

            for k in l:

                print(k + " : " + d[k])     # Printing the keys and values of dictionary in order of keys appearing in the sorted list.

        elif (choice=="6"): # Quit

            loop=False

            if modified:                    # Checking if dictionary has been modified after saving the file

                choice = input("Do you want to save the file before exiting? (Y for yes and N for no) ")   # Asking user whether to save file before exiting

                if choice == "Y" or choice == "y":

                    print("Saving the file")

                    file = open(filename,"w")       # Opening the file for writing

                    for k in d:

                        file.write(k + ", " + d[k] + "\n") # Writing the key and value to the file seperated by comma

                    file.close()                    # Closing the file

            print("Exiting the program!\n\n")

        else :

            print("Incorrect choice")

main()

SCREENSHOTS -

CODE -

OUTPUT -

If you have any doubt regarding the solution, then do comment.

Do upvote.


Related Solutions

Write a program in java that deliberately contains an endless or infinite while loop. The loop...
Write a program in java that deliberately contains an endless or infinite while loop. The loop should generate multiplication questions with single-digit random integers. Users can answer the questions and get immediate feedback. After each question, the user should be able to stop the questions and get an overall result. See Example Output. Example Output What is 7 * 6 ? 42 Correct. Nice work! Want more questions y or n ? y What is 8 * 5 ? 40...
Complete the following in syntactically correct Python code. Write a program, using a for loop, that...
Complete the following in syntactically correct Python code. Write a program, using a for loop, that calculates the amount of money a person would earn over a period of time if his or her salary is 1 penny for the first day, 2 pennies for the second day, 4 pennies for the third day, and continues to double each day. 1.      The program should ask the user for the number of days the employee worked. 2.      Display a table showing the salary...
complete a brief case analysis based on the article posted below. analyze the external environment as...
complete a brief case analysis based on the article posted below. analyze the external environment as well as the internal environment. http://fortune.com/2018/02/20/kfc-still-shut-uk/
PART A - STACKS To complete this assignment: Please study the code posted below. Please rewrite...
PART A - STACKS To complete this assignment: Please study the code posted below. Please rewrite the code implementing a template class using a linked list instead of an array. Note: The functionality should remain the same *************************************************************************************************************** /** * Stack implementation using array in C/procedural language. */ #include <iostream> #include <cstdio> #include <cstdlib> //#include <climits> // For INT_MIN #define SIZE 100 using namespace std; /// Create a stack with capacity of 100 elements int stack[SIZE]; /// Initially stack is...
Python Programming Revise the ChatBot program below. There needs to be one list and one dictionary...
Python Programming Revise the ChatBot program below. There needs to be one list and one dictionary for the ChatBot to use. Include a read/write function to the program so that the program can learn at least one thing and store the information in a text document. ChatBot program for revising: # Meet the chatbot Eve print('Hi there! Welcome to the ChatBot station. I am going to ask you a series of questions and all you have to do is answer!')...
Write a complete program to sum the following series: (hint: use the for loop) 1 /2...
Write a complete program to sum the following series: (hint: use the for loop) 1 /2 + 1/ 4 + 1 /6 + ⋯ + 1 /100 PS: use C++ language please
Write a complete program using the do-while loop that prompts the user to enter a string...
Write a complete program using the do-while loop that prompts the user to enter a string and displays its first and last characters. Repeat until the user enter a string that contains only one character. Here is an example to show you how the output may look like: <output> Enter a string ( type only one character to exit): this is my string The first character is t The last character is g Enter a string ( type only one...
Create a python program that contains a while loop together with a Sentinel (0) to process...
Create a python program that contains a while loop together with a Sentinel (0) to process indefinite item costs that are purchased online from a vendor. Be sure that you assign a variable SENTINEL to 0 to use in the Boolean condition of your while loop. A sales tax rate of 6.25% is applied to the subtotal for the items purchased. Be sure you assign a variable, TAXRATE to 0.0625. The program is to process a number of items, numItems,...
Loop Introduction Assignment Please write a program in c# Using the conditions below, write one program...
Loop Introduction Assignment Please write a program in c# Using the conditions below, write one program that calculates a person’s BMI. Your main() function will call functions 1, 2, and 3. Your program will contain three functions: Function #1: Will ask the user for their weight in pounds and their height in inches.   Your function will convert the weight and height into Body Mass Index (BMI). The formula for converting weight into BMI is as follows: BMI = Weight *...
(True or False) The following is an infinite loop. int main() { bool flag = false;...
(True or False) The following is an infinite loop. int main() { bool flag = false; int num = 0; while(!flag); { cin >> num; if(num == -1) { flag = true; } } return 0; }
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT