修改字典python中的值 [英] Modifying the value in the dictionary python

查看:174
本文介绍了修改字典python中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用itertools的文本文件字典.

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

结果是:

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

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

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

我想提示用户水果(键)的名称以同时修改键和描述(值)或删除整个记录.如果可以使用def()函数,那将是最好的.

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']} 

请帮帮我.谢谢

推荐答案

此解决方案适用于编辑之前的问题.先前在original_name输入中有一个.upper().修改后的代码如下:

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}.")

假设您的file.txt看起来像这样:

Assuming your file.txt looks like this:

banana
delicious, yellow

watermelon
big, red

orange
juicy, vitamin cc

这篇关于修改字典python中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆