简体   繁体   中英

Modifying the value in the dictionary python

I have a text file-turned-dictionary using itertools.

import itertools

plantfile = 'myplants.txt' #file path
plant = {} #create an empty dictionary
with open(plantfile, 'r') as f:
    for empty_line, group in itertools.groupby(f, lambda x: x == '\n'): 
        if empty_line:
            continue
        fruit, *desc = map(str.strip, group)
        plant[fruit] = desc

The result is:

{'banana' : ['delicious', 'yellow'],

'watermelon' : ['big', 'red'],

'orange' : ['juicy', 'vitamin c']} 

I would like to prompt the user the name of the fruit (key) to modify both the key and description (value) or delete the whole record. It would be the best if I can use def () function.

The following are my current codes. They do not return me any error messages, however, they are also not reflected back in the dictionary file.

    print("What do you want to do with this database?
    1. Modify fruit information
    2. Delete fruit record")
    
    choice == input("Please enter your choice in number: ")
    
    while True:
        try:
            if choice == '1':
               original_name = input("What is the fruit name you would like to modify?").upper()
               new_name = input("What is the new fruit name?")
            
               with open(file, 'r+') as f: 
               string = f.read() 
               string = string.replace(original_name, new_name) 
               f.truncate(0) 
               f.seek(0) 
               f.write(string) #writeback to file
               print(f"You have modified {original_name} to {new_name}.")
               break
            else:
               delname = input("Please enter the name of the fruit: \n").upper() 
               delname = dict(filter(lambda item: delname in item[0], plant.items())) 
               break
except ValueError:
    print("Invalid input. Please try again.")

I can't figure out how to modify the values and it seems like the above code to modify the name of the key isn't working either.

The code above to delete the whole record is also not being reflected in the original file.

for eg, I would like to change the value of watermelon from 'big' to 'hard' and wishes to delete the whole record of banana.

{'watermelon' : ['hard', 'red'],
    
    'orange' : ['juicy', 'vitamin c']} 

Please help me out. Thank you

This solution is for the question before the edit. There was an .upper() in the original_name input taken previously. The modified code is as follows:

import itertools

file = 'file.txt' 
plant = {} 
with open(file, 'r') as f:
    for empty_line, group in itertools.groupby(f, lambda x: x == '\n'): 
        if empty_line:
            continue
        fruit, *desc = map(str.strip, group)
        plant[fruit] = desc

print(plant)


original_name = input("What is the fruit name you would like to modify?")
new_name = input("What is the new fruit name?")
    
with open(file, 'r+') as f: 
    string = f.read()
    string = string.replace(original_name, new_name) 
    f.seek(0) 
    f.write(string) #writeback to file
print(f"You have modified {original_name} to {new_name}.")

Assuming your file.txt looks like this:

banana
delicious, yellow

watermelon
big, red

orange
juicy, vitamin cc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM