Optimization of english dictionary python program

python_3

#1

this program uses: python3, and only built-in/standard libraries

So i was following this course, in which we build a command line interface dictionary lookup, this is the code used by the solution:

import json
from difflib import get_close_matches

data = json.load(open("data.json"))

def translate(w):
    w = w.lower()
    if w in data:
        return data[w]
    elif len(get_close_matches(w, data.keys())) > 0:
        yn = input("Did you mean %s instead? Enter Y if yes, or N if no: " % get_close_matches(w, data.keys())[0])
        if yn == "Y":
            return data[get_close_matches(w, data.keys())[0]]
        elif yn == "N":
            return "The word doesn't exist. Please double check it."
        else:
            return "We didn't understand your entry."
    else:
        return "The word doesn't exist. Please double check it."

word = input("Enter word: ")
output = translate(word)
if type(output) == list:
    for item in output:
        print(item)
else:
    print(output)

data.json is just a json dictionary file:

https://gist.githubusercontent.com/stetim94/6afb9113bd766f97adc57a30834530af/raw/05c919e740fd507861ae5b9606f0085d05fffa2c/data.json

what are good ways to optimize this program?

my thoughts about optimization:

replacing if w in data with try/except to prevent an additional lookup in dictionary (in isn’t every fast)
i would store get_close_matches(w, data.keys(), n = 1) in a variable, so we only have to call this function once, rather then the three times, so my program would look something like:

import json
from difflib import get_close_matches

data = json.load(open("data.json"))

def translate(w):
    w = w.lower()
    try:
        return data[w]
    except KeyError:
        close_match = "".join(get_close_matches(w, data.keys(), n=1))
        if close_match:
            yn = input("Did you mean {} instead? Enter Y if yes, or N if no: ".format(close_match)).upper()
            if yn == "Y":
                return data[close_match]
            elif yn == "N":
                return "The word doesn't exist. Please double check it."
            else:
                return "We didn't understand your entry."
        else:
            return "The word doesn't exist. Please double check it."

word = input("Enter word: ")
output = translate(word)
if type(output) == list:
    for item in output:
        print(item)
else:
    print(output)