有一本字典有两种语言的三对水果。其中一个在英语中是不正确的(pomme-aple),可以由用户修复。此外,用户还可以在字典中添加两种语言的新词。如果用户不想添加新的水果或修复错误的水果,则可以退出词典。 新单词或固定单词应保存在dat文件中,但该文件仍为空:( 这是一个家庭作业,我必须用shelve解决这个问题,但我不知道如何解决。 以下是我的尝试:
import shelve
store = shelve.open("fruits.dat")
try:
mydict = store["allfruits"]
except:
mydict = {"pomme" : "aple", "poire" : "pear", "cerise" : "cherry"}
mydict = {"pomme" : "aple", "poire" : "pear", "cerise" : "cherry"}
while True:
answer=input("Write a fruits name ")
if answer == "pomme":
print(mydict["pomme"])
answer1=input("Would you like to change it? ")
if answer1 == "yes":
newworld=input("What's that? ")
mydict2 = {"pomme" : newworld}
mydict.update(mydict2)
anotherfruit=input("Thx. Are you interested in another fruits name? ")
if anotherfruit=="yes":
continue
else:
print("Bye")
break
else:
print("Bye")
break
elif answer not in mydict:
adding=input("It's not in there. Would you like to add? ")
if adding == "yes":
newworld1=input("How is it in English? ")
mydict3 = {answer : newworld1}
mydict.update(mydict3)
anotherfruit=input("Thx. Are you interested in another fruits name? ")
if anotherfruit=="yes":
continue
else:
print(mydict)
break
else:
print("Bye")
break
store["allfruits"] = mydict
store.sync()
store.close()
这里>
您尝试使用
mydict = store['allfruits']
从数据库中读取mydict
。如果失败(在except:
语句中),则为mydict
指定一个默认值。那部分很好但是,在您分配
mydict = { ... }
之后,立即再次覆盖您刚刚从数据库读取的内容相关问题 更多 >
编程相关推荐