'I had made a small dictionary, where i am asking user to find anything from the the dictionary. i want user to input string and numeric value [duplicate]
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.
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Philip Z. |
