使Python程序保存对其

2024-05-20 17:21:23 发布

您现在位置: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

Tags: toinyouinputif定义atdexit
1条回答
网友
1楼 · 发布于 2024-05-20 17:21:23

可以使用JSON将数据存储在文件中,在打开Python文件时读取其中的数据。你知道吗

我的_脚本.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)

数据.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"
}

相关问题 更多 >