Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write 3 functions in the starter code below such that: add to_dictl: takes a dic

ID: 3904873 • Letter: W

Question

Write 3 functions in the starter code below such that: add to_dictl: takes a dictionary, a key, a value and adds the key value pair to the dictionary. If key is already in dictionary then it displays the error message 'Error. Key already exists. Returns dictionary remove_from_dict): takes a dictionary and key and removes the key from the dictionary. Returns dictionary. If no such key is found in the dictionary then it prints: "No such key exists in the dictionary.. Hint: Use try-except. tind-key(dictt, key): takes dictionary and key and prints value coresponding to the key trom the dictionary, printrvalue", value). It key is not tound, then prints: .Key not tound." Hint: Use try-except ·

Explanation / Answer

Python3 Code:

def add_to_dict(d, k, v):

    if k in d:

        print("Error: key already exists.")

    else:

        d[k] = v

    return d

def remove_from_dict(d, k):

    try:

        del d[k]

    except KeyError:

        print("No such key exists in the dictionary.")

def find_key(d, k):

    try:

        print("Value: ", d[k])

    except KeyError:

        print("Key not found.")

       

def main():

    more = True

    dictt = {}

    dictlst = []

    while more:

        print("Menu: ")

        choice = input("add(a), remove(r), find(f): ")

        if choice.lower() == "a":

            key = input("Key: ")

            value = input("Value: ")

            dictt = add_to_dict(dictt, key, value)

        elif choice.lower() == "r":

            key = input("key to remove: ")

            dictt = remove_from_dict(dictt, key)

        elif choice.lower() == "f":

            key = input("Key to locate: ")

            find_key(dictt, key)

        else:

            print("Invalid choice.")

           

        do_more = input("More (y/n)? ")

        if do_more.lower() != 'y':

            more = False

    if dictt:

        for key, value in dictt.items():

            temp = (key, value)

            dictlst.append(temp)

        print(sorted(dictlst))

main()

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote