我如何制作它以便将更改保存到字典中?它将能够添加一个定义然后它将能够退出然后仍保持该定义
words = {
"orange": "naranja",
"hello": "hola",
"bye": "adiós",
"red": "rojo",
"blue": "azul",
"yellow": "amarillo",
"purple": "púrpura",
"green": "verde",
"white": "blanco",
"black": "negro",
"Ethan": "Yeet"
}
while 1 == 1:
tt = input("What would you like to translate? (Only write in lowercase and type EXIT to quit) ")
if str(tt) in words:
print(tt + " is " + words.get(tt, "Not in dictionary"))
elif str(tt) == "EXIT":
break
else:
atd = input("Would you like to add " + str(tt) + " to our dictionary? Y/N ")
if atd == "Y" or atd == "y":
d = input("What does it translate to? ")
d = str(d)
tt = str(tt)
words.update({tt: d})
print(tt + " is "+ words.get(tt, "What"))
continue
elif str(atd) == "EXIT":
break
else:
continue
答案 0 :(得分:0)
您可以使用JSON将数据存储在文件中,在打开Python文件时读取数据。
<强> my_script.py 强>
import json
with open('data.json', 'r') as f:
words = json.load(f)
#Do some things with your data here - maybe add some new values...
#Write updated data back to file.
with open('data.json', 'w') as f:
json.dump(words, f)
<强> data.json:强>
{
"orange": "naranja",
"hello": "hola",
"bye": "adiós",
"red": "rojo",
"blue": "azul",
"yellow": "amarillo",
"purple": "púrpura",
"green": "verde",
"white": "blanco",
"black": "negro",
"Ethan": "Yeet"
}