In: Computer Science
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()
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: