0
a = {"green":"hot","Rebukes":"reprimand",19: "my birthday"}
b=input("Enter the word of your choice")
print(a[b])

Error happens when I as a user give 19 as input to the program. I know that input function by default takes string value and I want user to access any key from the dictionary whether it is a string or integer or float.

buran
  • 13,682
  • 10
  • 36
  • 61
Msr
  • 1
  • 1
  • `input()` always return `str`. You need to convert to `int`. Also, have a look at `dict.get()` method that will prevent the `KeyError` on missing keys. Also, you can try to convert user input and handle the error if the key is not numeric, convertible t – buran Feb 13 '22 at 10:13
  • thanks buran for your lovely answer – Msr Feb 15 '22 at 16:26
  • a = {"green":"hot", "Rebukes":"reprimand", 19: "my birthday"} b = input("Enter the word of your choice") c = a.get("b") print(c) – Msr Feb 15 '22 at 17:03
  • hii buran, the last comment of mine was of the same code using get function but the output of it shows "none" after giving 19 as the input – Msr Feb 15 '22 at 17:05

1 Answers1

0

You read your input as a string so when you enter 19 your dictionary will look for the string key '19' instead of the integer 19. You could test if the input is a number and if it is, cast the string to an integer:

a = {"green":"hot", "Rebukes":"reprimand", 19: "my birthday"}
b = input("Enter the word of your choice")
if b.isnumeric():
    b = int(b)
print(a[b])

However, it might be a good idea to have the dictionary keys all of the same type.

Philip Z.
  • 206
  • 2
  • 6