Jeremy Wik
Jeremy Wik

Reputation: 63

Access value in dictionary with variable key

print(choices[userInput])

I have a dictionary called choices which has keys 1,2,3, and 4. I prompt the user for an input which is stored in the userInput variable. If the user enters 3, I would like to access the value that's at choices[3]. However, I keep getting Key Error 3. If I change the userInput in the print statement to 3, it returns the correct value

Upvotes: 3

Views: 1072

Answers (1)

GranolaGuy
GranolaGuy

Reputation: 132

User input is usually gotten with input(), which returns a string. If your keys are ints but you are using strings, it wont work. Check the types of your keys and what you are using to key into the dict. Make sure they are the same.

A better practice would be to check if the key is in the dict before keying in:

if userInput in choices:
    print(choices[userInput])
else:
    print("Invalid key")

Upvotes: 2

Related Questions