[英]Modifying the value in the dictionary python
我有一個使用 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()function就最好了。
以下是我當前的代碼。 他們不會返回任何錯誤消息,但是,它們也不會反映在字典文件中。
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.")
我不知道如何修改這些值,而且上面修改密鑰名稱的代碼似乎也不起作用。
上面刪除整個記錄的代碼也沒有反映在原始文件中。
例如,我想將西瓜的值從“大”更改為“硬”,並希望刪除香蕉的整個記錄。
{'watermelon' : ['hard', 'red'],
'orange' : ['juicy', 'vitamin c']}
請幫幫我。 謝謝
此解決方案適用於編輯前的問題。 之前獲取的original_name
輸入中有一個.upper()
。 修改后的代碼如下:
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
如下所示:
banana
delicious, yellow
watermelon
big, red
orange
juicy, vitamin cc
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.