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.

4
  • 1
    What do you mean by "it doesn't work the way I want"? What's your expected and/or unexpected output? Commented May 27, 2020 at 11:28
  • what is the problem you are facing ?? Commented May 27, 2020 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. Commented May 27, 2020 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? Commented May 27, 2020 at 12:26

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

It works for only one time. I want to create database. Like it will be a lot of key and values as user input.
thanks it works as I want, But now I want to save the output dictionary in json database
you want to save it as a JSON file or store it in a database like MongoDB?
I am a newbie at programing. So I have a little bit knowledge about databases. I only know json. So a JSON file
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.

8 Comments

It did not work, I get error called AttributeError: partially initialized module 'json' has no attribute 'dump' (most likely due to a circular import)
@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.
Okay, I am new at python. How do I check if there is a json.py file in the same folder or not?
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: stackoverflow.com/a/52093367/3129414
when I run code it takes values but do not print them.Instead it prints data.json string
|
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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.