2017-09-27 21 views
-1

我该如何制作它,以便将更改保存到字典中?这将能够添加一个定义,那么这将是能够然后退出仍然保持这一定义制作一个Python程序保存它对自己所做的更改

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

你这是什么意思,从技术上讲,你已经用'words.update({tt:d})'来做这件事。 –

+0

@JohnPerry听起来像这个问题是关于坚持这些变化的文件。 –

+0

@DavidZ这些也是我的想法,但在这种情况下,他需要阅读和写作。 –

回答

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" 
} 
+0

这似乎不适合我。 –

+0

你将不得不更具体。你是如何在代码中实现它的? –

相关问题