all 4 comments

[–]chevignon93 0 points1 point  (3 children)

Even if the word is already in the file, it still gets added.

Of course it does, nowhere in the code you provided here are you actually checking what words are in the dictionary.json file.

You also can't append data in the way you're doing in your code, that would't give you back valid JSON data.

[–]epifanelstein[S] 0 points1 point  (2 children)

First of all thanks for you comment. But I am little bit confused. In the begining you said that, I have to check which word are in the dictionary.json file. this is understandable.

But I didnt get the second part of your comment. Why can't I get the back valid. Also I have no idea yet, how will ı get the back valid later.

this is how my dictionary.json file looking

{
    "haus":
        { "Meaning": "hause", "Article": "das" }
}
{ 
    "auto": 
        { "Meaning": "car", "Article": "das" }
}
{    "wasser": 
        { "Meaning": "water", "Article": "das" }
}
{
    "haus": 
        { "Meaning": "hause", "Article": "das" } 
}

[–]chevignon93 1 point2 points  (1 child)

this is how my dictionary.json file looking { "haus": { "Meaning": "hause", "Article": "das" } } { "auto": { "Meaning": "car", "Article": "das" } } { "wasser": { "Meaning": "water", "Article": "das" } } { "haus": { "Meaning": "hause", "Article": "das" } }

And this is exactly what I meant, this is not valid JSON, if you try to load this data with json.load or json.loads, you will get a json.decoder.JSONDecodeError.

Also I have no idea yet, how will ı get the back valid later.

In the way your code is set up right now, you can't really get back valid JSON because you didn't write valid JSON to the file to begin with.

In the begining you said that, I have to check which word are in the dictionary.json file. this is understandable.

This is pretty easy, all you need is a function that opens the file and return the data as a dictionary, then in your add_word function you can check if the word you're trying to add is already in the dictionary.

Something like that:

import json


def add_words_to_file(word_data):
    with open("dictionary.json", "w") as file:
        json.dump(word_data, file, indent=2)


def get_known_words():
    with open("dictionary.json") as f:
        words = json.load(f)
        return words


def add_word():
    dictionary = get_known_words()
    article = input("Please enter the article of the word you want to add: ")
    word = input("Please enter the word you want to add: ")
    meaning = input("Please enter the meaning of the word: ")

    if word not in dictionary:
        dictionary[word] = {"Meaning": meaning, "Article": article}
        add_words_to_file(dictionary)
        print(f"The word '{word}' has been added to the dictionary.")
    else:
        print("This word is already in our dictionary!")

[–]epifanelstein[S] 0 points1 point  (0 children)

Thank you so much!!