简体   繁体   English

修改字典中的值 python

[英]Modifying the value in the dictionary python

I have a text file-turned-dictionary using itertools.我有一个使用 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.要是能用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.之前获取的original_name输入中有一个.upper() 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:假设您的file.txt如下所示:

banana
delicious, yellow

watermelon
big, red

orange
juicy, vitamin cc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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