Making dictionary as user input, then save it into json file

Viewed 716

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 Answers

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.

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.

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
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.

Related