gpt4 book ai didi

python - 制作字典作为用户输入,然后将其保存到json文件中

转载 作者:行者123 更新时间:2023-12-04 09:49:02 25 4
gpt4 key购买 nike

我正在尝试做一个字典数据库,就像实际的字典一样。用户输入关键字和含义,程序将其保存在数据库中。比如输入单词:rain,输入单词的意思:从云中落下的水滴,然后程序把它做成字典。到目前为止,我可以做到这一点,但它不能按我想要的方式工作。

class Mydictionary:
def __init__(self):
self.key=input("Please input word: ")
self.value=input("Please input meaning of the word: ")

def mydictionary(self):
self.dic={self.key:self.value}

Mydic=Mydictionary()
Mydic.mydictionary()

它只工作一次。我想尽可能多地保存关键字和值。我想创建一个字典数据库。

最佳答案

enter image description here

据我所知,正如您所解释的那样,它运行良好......

如果您想在单个对象中插入多个值,这将不起作用,因为您在调用构造函数时获得了唯一的输入。

你必须像这样实现它

import json

class Mydictionary:
def __inint__(self):
self.dic = {}

def mydictionary(self):
self.key=input("Please input word: ")
self.value=input("Please input meaning of the word: ")
self.dic[self.key] = self.value

def save(self, json_file):
with open(json_file, "w") as f:
json.dump(self.dic, f)

Mydic=Mydictionary()
Mydic.mydictionary()
Mydic.mydictionary()

# to save it in a JSON file
Mydic.save("mydict.json")

现在您可以调用该方法 n 次以添加 n 个条目...

您可以在下面查看@arsho 的答案,我认为这是一个很好的做法。适本地命名函数与他们正在执行的实际功能是很重要的。

关于python - 制作字典作为用户输入,然后将其保存到json文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62041943/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com