【问题标题】:Making dictionary as user input, then save it into json file将字典作为用户输入,然后将其保存到 json 文件中
【发布时间】:2020-09-14 10:11:57
【问题描述】:

我正在尝试做一个字典数据库,就像真正的字典一样。用户输入关键字和含义,程序将其保存在数据库中。比如输入词: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()

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

【问题讨论】:

  • “它不能按我想要的方式工作”是什么意思?您的预期和/或意外输出是什么?
  • 你遇到了什么问题??
  • 它只工作一次。我想尽可能多地保存关键字和值。我想创建一个字典数据库。
  • 你不能只使用标准的dict吗?为什么你必须定制它?在我看来,您只需要从用户那里获取输入并将其添加到字典中?

标签: python json database dictionary user-input


【解决方案1】:

据我所知,正如您所解释的那样,它工作得很好......

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

你必须像这样实现它,

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 的答案,我认为这是一个很好的做法。根据他们正在执行的实际功能适当地命名该功能很重要。

【讨论】:

  • 它只工作一次。我想创建数据库。就像它将有很多键和值作为用户输入。
  • 感谢它按我的意愿工作,但现在我想将输出字典保存在 json 数据库中
  • 您希望将其保存为 JSON 文件还是将其存储在 MongoDB 等数据库中?
  • 我是编程新手。所以我对数据库有一点了解。我只知道json。所以一个 JSON 文件
【解决方案2】:

要将新的key - value 对插入到您的字典中,您需要创建一个从用户那里获取数据的方法。

__init__ 中,您可以声明一个空字典,然后在insert 方法中,您可以从用户那里获取一个新条目。

此外,要显示字典的当前元素,您可以创建一个名为 display 的单独方法。

json 内置可以直接将字典类型的数据从一个json文件写入和读取。您可以从official documentation on json 阅读有关json 的信息。

import json
import os


class Mydictionary:
    def __init__(self, file_name):
        self.json_file = file_name
        if os.path.exists(file_name):
            with open(self.json_file, "r") as json_output:
                self.data = json.load(json_output)
        else:
            self.data = {}


    def insert(self):
        user_key = input("Please input word: ")
        user_value = input("Please input meaning of the word: ")
        self.data[user_key] = user_value
        with open(self.json_file, "w") as json_output:
            json.dump(self.data, json_output)

    def display(self):
        if os.path.exists(self.json_file):
            with open(self.json_file, "r") as json_output:
                print(json.load(json_output))
        else:
            print("{} is not created yet".format(self.json_file))

Mydic=Mydictionary("data.json")
Mydic.display()
Mydic.insert()
Mydic.insert()
Mydic.display()

输出:

data.json is not created yet
Please input word: rain
Please input meaning of the word: water droplets falling from the clouds
Please input word: fire
Please input meaning of the word: Fire is a chemical reaction that releases light and heat
{'rain': 'water droplets falling from the clouds', 'fire': 'Fire is a chemical reaction that releases light and heat'}

免责声明:这只是类和方法声明和使用的概念。您可以即兴发挥这种方法。

【讨论】:

  • 它不起作用,我收到一个名为 AttributeError 的错误:部分初始化的模块 'json' 没有属性 'dump'(很可能是由于循环导入)
  • @NihadQurbanov,代码运行良好。请确保您没有在同一文件夹中保留任何名为 json.py 的文件。会导致循环导入错误。
  • 好的,我是 python 新手。如何检查同一文件夹中是否有json.py文件?
  • 代码文件存放在哪里?在同一文件夹中检查是否有任何文件json.py。如果答案是肯定的,请将json.py 重命名为其他名称。您显示的错误不是这个问题的相关错误。这个答案可能会对您有所帮助:stackoverflow.com/a/52093367/3129414
  • 当我运行代码时,它接受值但不打印它们。而是打印 data.json 字符串
【解决方案3】:

试试:

import json

class MyDictionary:

    __slots__ = "dic",

    def __init__(self):
        self.dic = {}

    def addvalue(self):
        """Adds a value into the dictionary."""
        key=input("Please input word: ")
        value=input("Please input meaning of the word: ")
        self.dic[key] = value

    def save(self, json_file):
        """Saves the dictionary into a json file."""
        with open(json_file, "w") as f:
            json.dump(self.dic, f)

# Testing

MyDic = MyDictionary()
MyDic.addvalue()
MyDic.addvalue()

print(MyDic.dic) # Two elements
MyDic.save("json_file.json") # Save the file

【讨论】:

    【解决方案4】:
    class dictionary():
        def __init__(self):
            self.dictionary={}
    
        def insert_word(self,word):
            self.dictionary.update(word)
    
        def get_word(self):
            word=input("enter a word or enter nothing to exit: ")
            if word=="":
                return None
            meaning=input("enter the meaning: ")
            return {word:meaning}
    
        def get_dict(self):
            return self.dictionary
    
    
    if __name__ == "__main__":
        mydict=dictionary()
        word=mydict.get_word()
        while word:
            mydict.insert_word(word)
            word=mydict.get_word()
        print(mydict.get_dict())
    

    这将继续输入,直到你给它一个空值,然后在你停止时打印出字典。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-21
      • 2018-08-13
      • 2022-12-15
      • 2023-04-02
      • 1970-01-01
      • 2015-06-15
      • 2013-11-06
      • 1970-01-01
      相关资源
      最近更新 更多