Question

In: Computer Science

Write a Python program that allows the user to perform three operations (implemented as three functions)...

Write a Python program that allows the user to perform three operations (implemented as three functions) on a dictionary:

add_to_dict(): takes a dictionary, a key, a value and adds the <key,value> pair to the dictionary. If the key is already in the dictionary, then the program displays the error message: "Error. Key already exists.".
remove_from_dict(): takes a dictionary and key and removes the key from the dictionary. If no such key is found in the dictionary then the program prints: "Key not found."
find_key(): takes dictionary and key and returns the value associated with the key or None if not found. The program prints the value if found, else prints: "Key not found."
No printing should be done inside these three functions.

The user is presented with a menu and repeatedly offered to perform an operation until he/she quits.

Finally, a list of the key-value pairs in the dictionary is printed out.

The main program is given - do not change it.

Example 1:

Menu: 
(a)dd, (r)emove, (f)ind: a
Key: rich
Value: 1
More (y/n)? y
Menu: 
(a)dd, (r)emove, (f)ind: a
Key: alireza
Value: 2
More (y/n)? n
[('alireza', '2'), ('rich', '1')]

def main():
    more_input = True
    a_dict = {}
  
    while more_input:    
        choice = menu_selection()
        execute_selection(choice, a_dict)
        again = input("More (y/n)? ")
        more_input = again.lower() == 'y'
  
    tuple_list = dict_to_tuples(a_dict)
    print(sorted(tuple_list))

main()

Solutions

Expert Solution

def add_to_dict(d, key, value):
    if key not in d:
        d[key] = value
        return 1
    else:
        return 0


def remove_from_dict(d, key):
    if key in d:
        del d[key]
        return 1
    else:
        return 0

def find_key(d, key):
    if key in d:
        return d[key]
    else:
        return None

def execute_selection(choice, a_dict):
    if(choice.lower()=="a"):
        key = input("Key: ")
        value = input("Value: ")
        result = add_to_dict(a_dict,key, value)
        if result==0:
            print("Error. Key already exists.")
    elif(choice.lower()=="r"):
        key = input("Key: ")
        result = remove_from_dict(a_dict, key)
        if result==0:
            print("Key not found.")
    elif(choice.lower()=="f"):
        key = input("Key: ")
        result = find_key(a_dict, key)
        if result==None:
            print("Key not found.")
        else:
            print(result)


def menu_selection():
    choice = input("Menu: (a)dd, (r)emove, (f)ind: ")
    return choice
def dict_to_tuples(d):
    list = [(k, v) for k, v in d.items()]
    return list
def main():
    more_input = True
    a_dict = {}
  
    while more_input:    
        choice = menu_selection()
        execute_selection(choice, a_dict)
        again = input("More (y/n)? ")
        more_input = again.lower() == 'y'
  
    tuple_list = dict_to_tuples(a_dict)
    print(sorted(tuple_list))

main()

NOTE: The above code is in Python3. Please refer to the attached screenshots for code indentation and sample I/O.


SAMPLE I/O:


Related Solutions

Write in Python and as 2 seperate programs Write a program that allows the user to...
Write in Python and as 2 seperate programs Write a program that allows the user to enter the total rainfall for each of 12 months into a LIST. The program should calculate and display the total rainfall for the year, the average monthly rainfall, and the months with the highest and lowest rainfall amounts. Data: January 7.9 inches February 10.1 inches March 3.4 inches April 6.7 inches May 8.9 inches June 9.4 inches July 5.9 inches August 4.1 inches September...
Use Visual Python or equivalent, to write a program that allows the user to observe the...
Use Visual Python or equivalent, to write a program that allows the user to observe the following: Damped and forced harmonic oscillators. The program should be user friendly and have default values for the initial velocities, positions, masses, and spring constants as well as damping constants. Values and frequencies for the forced oscillators should also be given. It should allow the user to input values for the velocities, positions, spring constants, and masses. The program should determine automatically the scale...
Write a Python program that allows the user to enter the total rainfall for each of...
Write a Python program that allows the user to enter the total rainfall for each of 12 months into a LIST. The program should calculate and display the total rainfall for the year, the average monthly rainfall, and the months with the highest and lowest rainfall amounts. Data: January 7.9 inches February 10.1 inches March 3.4 inches April 6.7 inches May 8.9 inches June 9.4 inches July 5.9 inches August 4.1 inches September 3.7 inches October 5.1 inches November 7.2...
In Python, write a program that allows the user to enter a number between 1-5 and...
In Python, write a program that allows the user to enter a number between 1-5 and returns the vitamins benefits based on what the user entered. The program should: Continue to run until the user quits and Validate the user’s input (the only acceptable input is 0, 1, 2, 3, 4, or 5), If the user enters zero “0” the program should terminate You can use the following facts: 1- Vitamin A protects eyes from night blindness and age-related decline...
In Python, write a program that allows the user to enter a number between 1-5 and...
In Python, write a program that allows the user to enter a number between 1-5 and returns the vitamins benefits based on what the user entered. The program should: Continue to run until the user quits and Validate the user’s input (the only acceptable input is 0, 1, 2, 3, 4, or 5), If the user enters zero “0” the program should terminate You can use the following facts: 1- Vitamin A protects eyes from night blindness and age-related decline...
USING PYTHON. Thank you in advance Write a program that allows the user to enter a...
USING PYTHON. Thank you in advance Write a program that allows the user to enter a series of string values into a list. When the user enters the string ‘done’, stop prompting for values. Once the user is done entering strings, create a new list containing a palindrome by combining the original list with the content of the original list in a reversed order. Sample interaction: Enter string: My Enter string: name Enter string: is Enter string: Sue Enter string:...
language python use a functions and write a python of a computer with three power operations:...
language python use a functions and write a python of a computer with three power operations: power by two, power by three, and power by four. input a number and operation (^2,^3,or^4). output: the result of the power operation
PYTHON (BEGINNER) program that allows the user to choose any of the three sports options described...
PYTHON (BEGINNER) program that allows the user to choose any of the three sports options described below and computes the relevant statistic in each case: Quidditch Score Total: Determined based on the number of goals and whether or not the snitch was caught. A goal is scored by propelling the quaffle through a hoop and each earns the team 10 points. If a team catches the snitch, that team earns an additional 30 points. The snitch can be caught at...
Write a program using Python that allows the user to play a guessing game (please provide...
Write a program using Python that allows the user to play a guessing game (please provide a picture of code so it is easier to read). The game will choose a "secret number", a positive integer less than 10000. The user has 10 tries to guess the number. Requirements: Normally, we would have the program select a random number as the "secret number". However, for the purpose of testing your program (as well as grading it), simply use an assignment...
Fraction calculator: Write a program that lets the user perform arithmetic operations on fractions.
Fraction calculator: Write a program that lets the user perform arithmetic operations on fractions. Fractions are of the form a / b, in which a and b are integers and b != 0.Your program must:be menu driven, allowing the user to select the operation (+, -, *, or /) and input the numerator and denominator of each fraction.The input must be validated for correct operation (+, -, *, or /) and b != 0. If any of these cases are...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT