value in key,value pair of dictionaries cant be iterated over in a function

Question:

This code works so that when I give an input word, if it matches exactly with a term stored in a dictionary, it prints the definition of asked term. A caveat I am trying to add is if I give an input that is similar to a term in the dictionary, I do a little check, if any part of the input, is stored as termin the dictionary.

word = input("Enter a programming term you want to know about: ")
terms = {
    "tuple" : "Variables are containers for storing data (storing data values)."
}


def return_definition(word):
    output = ""
    for term, value in terms:
        if word == term :
            output += terms.get(key)
        elif term in word:
            output += terms.get(value)
    return output

print(return_definition(word))

The elif conditional tests if the user inputs "tuples". I would like to return the value of tuple to them, and check term in word, so the program returns the value for tuples nevertheless. However, instead of return the definition, the program causes this error

Traceback (most recent call last):
  File "e:CodePython CodeExercisesdictionary.py", line 48, in <module>        
    print(returnDefinition(word))
  File "e:CodePython CodeExercisesdictionary.py", line 41, in returnDefinition
    for term, value in terms:
ValueError: too many values to unpack (expected 2)
Asked By: Illusioner_

||

Answers:

If you really need to iterate through the dictionary, you should do like so:

for key, value in terms.items():
    if key in termToKnow:
        output += value

Note that this can lead to you outputting multiple different values. What if user for examples just types "a"? How many results could that possibly yield? What do you want to do in that case? Return the first value that has an "a" in it? You will need to think about these questions to find the best approach.

Answered By: Filip Müller

Here is what I would do:

def returnDefinition(termToKnow, terms):
    output = ""
    # We loop through the words in termToKnow instead of looping through the dictionary
    for word in termToKnow.split(' '):
        if word in terms:
            output += terms[word]
    return output

If you want to match if there is a random character before or after the term (pythonk instead of python):

def returnDefinition(termToKnow, terms):

    # Check if there is an exact match
    if termToKnow in terms:
        return terms[termToKnow]
    else:
        # Check for match with a mistyped character
        for key in terms.keys():
            if key in termToKnow:
                return terms[key]

    return "Didn't find anything"    
Answered By: stelioslogothetis
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.