Tuesday 12 February 2019

Python: Fastest way to retrieve element from dictionary

Some helpful reading about the dictionary from python docs here.

Here is something from the stackoverflow.

Here is a program that checks and retrieves the values for keys in a dictionary:

data = {'one': 1, 'two': 2, 'three': 3}
 
def translate(word):
    # The below line gets the value from 
    # the dictionary if the key is present 
    # in the dictionary. It will return None 
    # if the key is not in the dictionary. 
    # But its slow 
 
    definition = data.get(word, None)

    # The below line is fast and checks if the
    # key is in the dictionary 
 
    if word in data:
        return data[word]
    else:
        return "No definition found for the word"
 
   # This below is an also alternative 
    try:
        return data[word]
    except KeyError:
        return "No definition found for the word"


word = input("Enter a word: ")
print(translate(word=word))