有一本字典,其中有3对水果,用两种语言。其中一个在英语中不正确(pomme - aple),可以由用户修正。另外,用户可以在2种语言的字典中添加新词。如果不想添加新的水果或修正错误的水果,用户可以退出字典。新的或修正的单词应该保存在一个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()
在这里-->。
try:
mydict = store["allfruits"]
except:
mydict = {"pomme" : "aple", "poire" : "pear", "cerise" : "cherry"}
mydict = {"pomme" : "aple", "poire" : "pear", "cerise" : "cherry"}
while True:
...
您尝试阅读 mydict
从数据库中获取 mydict = store['allfruits']
. 如果失败(在 except:
语句),您分配给 mydict
一个默认值。 这一部分很好。
但是在你将 mydict = { ... }
再次覆盖刚才从数据库中读取的内容。