2017-09-27 5 views
-1

辞書に変更を保存するにはどうすればよいですか?まだあなたがあなたのPythonのファイルを開くときは、データを読み込み、ファイルにデータを保存するためにJSONを使用することができ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

その定義を保持し、その後出ることができるようになる定義を追加することができます。

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

あなたはもっと具体的にする必要があります。これをあなたのコードにどのように実装しましたか? –

関連する問題