2017-09-27 57 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

你將不得不更具體。你是如何在代碼中實現它的? –

相關問題