2

I am trying to do a dictionary database, like actual dictionary. User input key word and meaning and program saves it in database. Like input word: rain , input meaning of the word: water droplets falling from the clouds then program makes it a dictionary. So far I can manage do this but it doesn't work the way I want.

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()

It works for only one time. I want to save keywords and values as much as I want. I want to create a dictionary database.

arshovon
  • 13,270
  • 9
  • 51
  • 69
  • 1
    What do you mean by "it doesn't work the way I want"? What's your expected and/or unexpected output? – ghost May 27 '20 at 11:28
  • what is the problem you are facing ?? – San May 27 '20 at 11:35
  • It works for only one time. I want to save keywords and values as much as I want. I want to create a dictionary database. – Nihad Qurbanov May 27 '20 at 11:43
  • Couldn't you just use the standard `dict`? Why do you have to customize it? From what I see, you only need to take input from the user and add it to the dictionary? – Eric Jin May 27 '20 at 12:26

4 Answers4

1

enter image description here

As far as I could see, it is working perfectly as you explained...

If you were thinking that you want to insert many values in a single object, this won't work as you are getting the only one input while calling the constructor.

You have to implement it like,

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")

Now you can call the method n times to add n entries...

You can look at the answer by @arsho below which I would consider as a good practice. Naming the function appropriately wrt the actual function they are doing is important.

San
  • 453
  • 3
  • 14
1

To insert new key - value pair to your dictionary, you need to create a method to get data from the user.

In __init__ you can declare an empty dictionary and then in insert method you can get a new entry from the user.

Moreover, to display the current elements of the dictionary you can create a separate method with name display.

json built-in can directly write and read dictionary type data from an to a json file. You can read about json from official documentation on 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()

Output:

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'}

Disclaimer: This is just a concept of class and method declaration and usage. You can improvise this approach.

arshovon
  • 13,270
  • 9
  • 51
  • 69
  • It did not work, I get error called AttributeError: partially initialized module 'json' has no attribute 'dump' (most likely due to a circular import) – Nihad Qurbanov May 27 '20 at 12:08
  • @NihadQurbanov, the code is working fine. Please ensure you are not keeping any file named `json.py` in the same folder. It will cause the circular import error. – arshovon May 27 '20 at 12:16
  • Okay, I am new at python. How do I check if there is a json.py file in the same folder or not? – Nihad Qurbanov May 27 '20 at 12:17
  • Where are you storing the code file? In the same folder check if there is any file `json.py`. If the answer is yes, rename `json.py` to something else. The error you have shown is not a relevant error of this question. This answer may help you: https://stackoverflow.com/a/52093367/3129414 – arshovon May 27 '20 at 13:04
  • when I run code it takes values but do not print them.Instead it prints data.json string – Nihad Qurbanov May 27 '20 at 13:12
  • @NihadQurbanov, please copy, paste my current code from here. I have rechecked it and it is displaying the value. May be your code file includes code from my old answer. – arshovon May 27 '20 at 13:18
  • sorry my mistake, I missed something. thanks but when I run the program again it delete old dictionary and adds new values to it. This is not the thing I want. I want database which I keep word meanings in it. It must be keep old key and values and append new ones to it – Nihad Qurbanov May 27 '20 at 13:31
  • @NihadQurbanov, I have updated the code for storing the dictionary data into flat file. It will append new values from now on. – arshovon May 27 '20 at 13:52
0

Try:

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
TheOneMusic
  • 1,776
  • 3
  • 15
  • 39
0
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())

this will keep taking inputs until you give it a null value and then print out the dictionary when u stop.