In: Computer Science
Create two functions that you can use for a dictionary manager:
1. remove_item(dictionary,key): a function that removes the item with the supplied key from the dictionary, if it exits. If the input key doesn’t exist in the dictionary, print out a message saying that the new item has not been removed because there is no matching key in the dictionary. Your function should not produce a Python error if the item does not exist;
2. add_new_item(dictionary,key,value): a function that adds a new item to the dictionary (using the input key and value) if there is no existing item in the dictionary with the supplied key. If the input key already exists in the dictionary, print out a message saying that the new item has not been added because there is already a matching key in the dictionary. No Python error should be raised by this fuction if the key already exists.
Test out your functions by creating a dictionary with several items and then doing four (4) things:
removing an item that exist;
removing an item that doesn’t exist;
adding an item whose key doesn’t exist;
adding an item whose key does exist;
Print out the contents of the dictionary after each of these tests and include the output of running your code as a comment in your submission.
We use python for this course
SOURCE CODE:python
*Please follow the comments to better understand the code.
**Please look at the Screenshot below and use this code to copy-paste.
***The code in the below screenshot is neatly indented for better understanding.
def remove_item(dictionary, key):
# Check if the key exists
if key in dictionary:
# Remove the key
del dictionary[key]
else:
# Key doesn't exist
print('The new item has not been removed because there is no matching key in the dictionary.')
def add_new_item(dictionary, key, value):
# Check if the key exists
if key in dictionary:
print('The new item has not been added because there is already a matching key in the dictionary. ')
else:
# Key doesn't exist
# So, add the key and value
dictionary[key] = value
# TEST the functions
# create an empty dictionary
dictionary = dict()
print("The dictionary is:", dictionary)
# 1. try removing a key from dictionary
print('1. try removing a key from dictionary')
remove_item(dictionary, 10)
print("\nThe dictionary is:", dictionary)
# 2. add some items
print('# 2. add some items')
add_new_item(dictionary, 'name', 'praveen')
add_new_item(dictionary, 'age', 24)
add_new_item(dictionary, 'city', 'LA')
print("\nThe dictionary is:", dictionary)
# 3. try deleting an existing item
print('# 3. try deleting an existing item')
remove_item(dictionary, 'city')
print("\nThe dictionary is:", dictionary)
# 4. try adding an existing item
print('# 4. try adding an existing item')
add_new_item(dictionary, "name", "Raju")
print("\nThe dictionary is:", dictionary)
===========