For reference, I am using Python 3.0. So, I have a small script I am working on trying to improve. I am now trying to create it with only dictionaries and loops.

My problem is that I keep getting a Key Error at one of my lines. The line with the error has an "Error" comment. Also, "words" is a dictionary. And yes, I struggle with dictionaries.
Code:

def vocabtest():
    for r in words.values():
        count = 0
        while count < 3:
            print("What word does the following definition correspond with?")
            print(r)
            answer = input("> ")
            if answer == words[r]: #Error
                print("Correct!")
                count = 100000
            elif count < 2:
                count = count + 1
                print("That is incorrect. Try again.")
            elif count == 2:
                count = count + 1
                print("That is incorrect. The answer was",str(words[r]) + ".")
                fail[r] = words[r]

If it is not obvious, I am printing the definition of the word, and requesting the user to input the word that matches the definition.

Any help to what is the cause of my error would be greatly appreciated. Thanks.

On line 2, r is coming from the values in the dictionary, not the keys.
So you can't use it as a key on line 8, you can't index a dictionary by the definition.

You could either test to see if the answer is a key and if it is, if the value matches the definition you have.

Alternatively (and probably better) iterate the keys on line 2 and then don't print the key, but print what you lookup from the dictionary using the key on line 6. Then you can just compare the answer with the key value.

commented: A big help. Followed through. +1

Thanks Murtan, but just one little question about your suggestion. So, so far I have changed line 8 to be "if answer in words.keys():". However, what would be the best way to check if the word also corresponds to the definition?

if words[answer] == r

Thank you very much Murtan. Problem solved.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.