Question: [Question] What changes can i make to the function deleteSelectedPlantInfo() to allow users to choose exactly what information they will like to remove? Ihave a

[Question]

What changes can i make to the function deleteSelectedPlantInfo() to allow users to choose exactly what information they will like to remove?

Ihave a dictionary the below in PYTHON that is recorded in txt file. please note that I am NOT using json

{'Monstera Deliciosa': {'plantname': 'Monstera Deliciosa', 'dateTime_of_record_created': '2018-11-03 18:21:26', 'info': ['Tropical/sub-Tropical plant', 'Leathery leaves, mid to dark green', 'Moist and well-draining soil', 'Semi-shade/full shade light requirements', 'Water only when top 2 inches of soil is dry', 'Intolerant to root rot', 'Propagate by cuttings in water']}, 'Strelitzia Nicolai (White Birds of Paradise)': {'plantname': 'Strelitzia Nicolai (White Birds of Paradise)', 'dateTime_of_record_created': '2018-11-05 10:12:15', 'info': ['Semi-shade, full sun', 'Dark green leathery leaves', 'Like lots of water,but soil cannot be water-logged', 'Like to be root bound in pot']}, 'Alocasia Macrorrhizos': {'plantname': 'Alocasia Macrorrhizos', 'dateTime_of_record_created': '2019-01-03 15:29:10', 'info': ['Tropical asia', 'Moist and well-draining soil', 'Leaves and stem toxic upon ingestion', 'Semi-shade, full sun', 'Like lots of water, less susceptible to root rot', 'Susceptible to spider mites']}, 'Caladium White Christmas': {'plantname': 'Caladium White Christmas', 'dateTime_of_record_created': '2020-03-07 10:10:20', 'info': ['Partial sun to bright full shade', 'Direct sun might burn Leaves', 'Water regularly and never allow soil to dry out', 'Soil must be loose and well draining']}, 'Sansevieria Trifasciata (Snake Plant)': {'plantname': 'Sansevieria Trifasciata (Snake Plant)', 'dateTime_of_record_created': '2020-05-22 09:56:49', 'info': ['Full shade to full sun', 'Well-draining soil', 'Water only when top 1 inch of soil is dry', 'Propagate by cuttings', '']}} 

I created a function at the below however i face a problem when user chose choice 2 (To a particular information)

Example:

User input to remove a particular information in "Sansevieria Trifasciata (Snake Plant)"

User then to be given a choice to delete information of their choice:"Water only when top 1 inch of soil is dry"

Expected output in dictionary ('Water only when top 1 inch of soil is dry' from Sansevieria Trifasciata (Snake Plant) to be removed from dictionary):

{'Monstera Deliciosa': {'plantname': 'Monstera Deliciosa', 'dateTime_of_record_created': '2018-11-03 18:21:26', 'info': ['Tropical/sub-Tropical plant', 'Leathery leaves, mid to dark green', 'Moist and well-draining soil', 'Semi-shade/full shade light requirements', 'Water only when top 2 inches of soil is dry', 'Intolerant to root rot', 'Propagate by cuttings in water']}, 'Strelitzia Nicolai (White Birds of Paradise)': {'plantname': 'Strelitzia Nicolai (White Birds of Paradise)', 'dateTime_of_record_created': '2018-11-05 10:12:15', 'info': ['Semi-shade, full sun', 'Dark green leathery leaves', 'Like lots of water,but soil cannot be water-logged', 'Like to be root bound in pot']}, 'Alocasia Macrorrhizos': {'plantname': 'Alocasia Macrorrhizos', 'dateTime_of_record_created': '2019-01-03 15:29:10', 'info': ['Tropical asia', 'Moist and well-draining soil', 'Leaves and stem toxic upon ingestion', 'Semi-shade, full sun', 'Like lots of water, less susceptible to root rot', 'Susceptible to spider mites']}, 'Caladium White Christmas': {'plantname': 'Caladium White Christmas', 'dateTime_of_record_created': '2020-03-07 10:10:20', 'info': ['Partial sun to bright full shade', 'Direct sun might burn Leaves', 'Water regularly and never allow soil to dry out', 'Soil must be loose and well draining']}, 'Sansevieria Trifasciata (Snake Plant)': {'plantname': 'Sansevieria Trifasciata (Snake Plant)', 'dateTime_of_record_created': '2020-05-22 09:56:49', 'info': ['Full shade to full sun', 'Well-draining soil', 'Propagate by cuttings', '']}}

# the function I want to improve on is at the below

#function delete selected plant info to the selected plant

def deleteSelectedPlantInfo():

allinfo = []

exist_info = plant_dict.get(user_input).get('info') #get nested dictionary info value

allinfo = exist_info #place existing info into list info

allinfo.clear()

writeDict()

print("Plant info deleted")

*******************************************************************************************************************************************************

#full code in python

filename = "myplants.txt" #to define the filename. in the event there is a change of file name, just change here.

# creating a dictionary

plant_dict = {}

f = open(filename, "r")

# read the file and split using empty line

for row in f.read().split(' '):

if row.strip() == '':

continue

li = row.split(' ')# Store information of a single plant in dicionary

plant_details = {}

plant_details["plantname"] = li[0]

plant_details["dateTime_of_record_created"] = li[1]

plant_details["info"] = li[2:]

plant_dict[li[0]] = plant_details# Store each plant dictionary to another dictionary

f.close()

#function to add new plant Name with timestamp on the condition that user input the plant name

def addPlantInfo():

#print('Plant is does not exist in your record')

from datetime import datetime #datetime librarie can get us Date and Time in a DateTime Object

file = open(filename,'a') #to define while file to open file and mode.

def getTimeStamp():

now = datetime.now() #We get this object, but notice this objects is not printable as it is not a string

date = now.strftime("%Y-%m-%d %H:%M:%S ") #then we convert that object into string and we organize the values as we please in this case YYYY=MM-DD HH:MM:SS

return date #we return this formatted string

dateTimeStamp = getTimeStamp() #every time we name a plant, we get the timeStamp and then it is printed

lines = []

while True:

information = input("Enter new plant information, you can enter in multiple lines. Leave blank to move on to next try or to exit: ")

if information:

lines.append(information)

else:

break

information = ' '.join(lines)

file.write(" " + user_input + " ")

file.write(dateTimeStamp + " ")

file.write(information + " ")

file.close()

#function delete selected plant info to the selected plant

def deleteSelectedPlantInfo():

allinfo = []

exist_info = plant_dict.get(user_input).get('info') #get nested dictionary info value

allinfo = exist_info #place existing info into list info

allinfo.clear()

writeDict()

print("Plant info deleted")

#function add plant info to the selected plant

def addSelectedPlantInfo():

allinfo = []

exist_info = plant_dict.get(user_input).get('info') #get nested dictionary info value

allinfo = exist_info #place existing info into list info

while True: #allow users to enter multiple lines

info = input("Enter new plant information (leave blank to end): ")

if info:

allinfo.append(info)

else:

break

writeDict()

print("Plant info added")

def writeDict():

#file = open(filename,'w') #to define while file to open file and mode.

#can this be a function?

f = open(filename, "w")

for key, value in plant_dict.items():

print(key)

# Again iterate over the nested dictionary

for key2, val2 in value.items():

#DES- check if type list

if type(val2) == list:

for singleListItem in val2:

print(singleListItem)

getText2 = singleListItem+" "

f.write(getText2)

else:

print(val2)

getText = val2+" "

f.write(getText)

#new line

f.write(" ")

f.close()

#function to sort by plantname

def sortplantname():

key_list = list(plant_dict.keys()) #define key_list

key_list.sort()

sorted_by_keys = {} #empty dictionary to hold the sorted keys

for each in key_list:

sorted_by_keys[each] = plant_dict[each]

print(sorted_by_keys)

print("")

print("This is the list of plants by Name in alphabetical order:")

for key, value in sorted_by_keys.items():

#print(key)

print("")

for key2, val2 in value.items():

#DES- check if type list

ind = 0

if type(val2) == list:

for singleListItem in val2:

ind = ind+1

getText2 = key2 +" : "+singleListItem

print(ind, ". ",getText2)

else:

#print(val2)

getText = key2 +" : "+ val2

print(getText)

#function to sort by timeofrecord. this one need to be updated, somehow this one dun work

def sorttimeofrecord():

items = sorted(plant_dict.items(), key = lambda tup: (tup[1]["dateTime_of_record_created"]), reverse = True)

print("")

print("This is the list of plants from latest Record Datetime:")

for key, value in items:

#print(key)

print("")

for key2, val2 in value.items():

#DES- check if type list

ind = 0

if type(val2) == list:

for singleListItem in val2:

ind = ind+1

getText2 = key2 +" : "+singleListItem

print(ind, ". ",getText2)

else:

#print(val2)

getText = key2 +" : "+ val2

print(getText)

#function to menu to display records in dictionary

def check_valid(): #this set of integer is writtened to check for the validity of client's input value

while True:

try:

print("What do you want to do ")

print("1.Sort All Records by Plant Name, 2. Sort All Records by Date/Time of Record Entry, 3. Enter Plant Name ")

Menu_Display_Records = int(input("Select your option: ")) #client must enter an integer value

return Menu_Display_Records #if client enter a non integer value, system will return to the same question "Please input your age:"

except ValueError:

print("Please enter either option 1, 2, or 3") #if client enter a non integer value, system will prompt this statememt

Menu_Display_Records = check_valid()

while Menu_Display_Records > 3: #user input other integer which is >3

print("Please enter either option 1, 2 or 3 ") #user will be prompted this statement

Menu_Display_Records = check_valid() #return back to the previous menu so he/she can choose again

if int(Menu_Display_Records) == 1: #if user choose a value = 1

sortplantname() #dictionary will be sorted by plantname

elif int(Menu_Display_Records) == 2: #if user choose a value = 2

sorttimeofrecord() #dictionary will be sorted by timeofrecord

else:

#function check validity of user input when they choose the menu

def check_valid(): #this set of integer is writtened to check for the validity of client's input value

while True:

try:

print("What do you want to do ")

print("1. Add new plant information","2. Delete a record plant information",f"3. Delete all current record information of {user_input}")

Menu = int(input("Select your option: ")) #client must enter an integer value

return Menu #if client enter a non integer value, system will return to the same question ""Select your option:"

except ValueError:

print("Please enter either option 1, 2, or 3") #if client enter a non integer value, system will prompt this statememt

user_input = input('Enter the plant name you want to input: ').strip()

print("")

if user_input in plant_dict: #if record of plantname is found in the dictionary

print('Plant is already in your record with the following information') #system will prompt that information is recorded

print(f"Date/Time of Record Entry:{plant_dict[user_input]['dateTime_of_record_created']} ") #then it will display data entry date/time record related to what user has input

print(f"Plant Information:{plant_dict[user_input]['info']} ") #then it will display information related to what user has input

Menu = check_valid()

while Menu > 3:

print("Please enter either option 1, 2 or 3 ") #if client enter a non integer value, system will prompt this statememt

Menu = check_valid() #if client enter a non integer value, system will return to the same question ""Select your option:"

#need to give user a chose to update or delete the record

if int(Menu) == 1: #if user choose a value = 1

addSelectedPlantInfo() #system will prompt for to ask user input more information have to check and confirm this one

elif int(Menu) == 2: #if user choose a value = 2

delete_plant_info()

#deleteSelectedPlantInfo()

#del(plant_dict[user_input]['info']) #system will delete the existing information and any additional information written in will related to plantname replace all exisiting information

#addPlantInfo() #system will prompt to add in more information to the exisiting plantname which user has input

#print(plant_dict) # to print the updated dictioary

elif int(Menu) == 3: #if user choose a value = 3

del plant_dict[user_input] #the entire entry for the plantname will be removed from the dictionary

writeDict()

print(user_input, "Record of plant is deleted") # to print the updated dictioary

else:

print('Plant is does not exist in your record')

addPlantInfo()

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!