Home > Software engineering >  value in key,value pair of dictionaries cant be iterated over in a function
value in key,value pair of dictionaries cant be iterated over in a function

Time:07-30

I am using a dictionary to return the definition of asked programming term

def returnDefinition(termToKnow, terms):
    output = ""
    for key, value in terms.items():
        if termToKnow == key :
            output  = terms[value]
        else:
            term_in_word = key in termToKnow
            if term_in_word:
                output  = terms[value]

Here, termToKnow inputted by the user, terms is the dictionary from which key value pairs are acessed. However, now the program throws an error.

Traceback (most recent call last):
  File "e:\Code\Python Code\Exercises\dictionary.py", line 31, in <module>        
    returnDefinition(termToKnow, terms)
  File "e:\Code\Python Code\Exercises\dictionary.py", line 29, in returnDefinition
    output  = terms[value]
KeyError: "Tuples are like lists, but can't be changed after assignment"

This worked out just fine outside a function in a normal for loop. How do I get the code to work inside a function

CodePudding user response:

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"    

CodePudding user response:

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.

  • Related