Python Forum

Full Version: Help! Functions
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi everyone! I am trying to create an English Thesaurus which the user is going to write an word as input and get the corresponding meaning, also if the user inputs a non-existing word than program has to output the variable m.
Unfortunately my code outputs m either way.
I'll be appriciated any help of you, thanks.
import json
data = json.load(open("data.json"))

def dictioanry(inp):
    m = "The word doesn't exist. Please double check it."
    for k in data.keys():
            if inp != k:
                return m
            else:
                answer = data[k]
                return answer

    
print(dictioanry(inp = input("Enter Word: "))) 
Output:
Enter Word: rain The word doesn't exist. Please double check it.
And this is what corresponds to rain in data:
Output:
>>> data["rain"] ['Precipitation in the form of liquid water drops with diameters greater than 0.5 millimetres.', 'To fall from the clouds in drops of water.']
At line 6, you're looping over the keys in the dictionary (which if it's a recent version of python will return the keys in the same order they were created).

When the loop starts, you then check the input against that first key and return success or failure. So the loop never continues and you never check any more keys.

If you want to loop over all the keys, you'd need to avoid returning on failure, but wait until the loop finishes.

Instead of looping over it you can ask if the key exists in the dictionary already.

if inp in data:
    # key exists already print definition.
    ...
else:
    # key not in dictionary.  Whine.
    ...
Was it easy like that! Thank you, I appreciate it.
no need to check the key exists, just use dict.get() method

import json
 
def meaning(word, dictionary):
    return dictionary.get(word, "The word doesn't exist. Please double check it.")

with open("data.json") as f:
    dictionary = json.load(f)
word = input("Enter Word: ")
print(meaning(word, dictionary))