'How can I use the variable input into a python dictionary?
Good day everyone, May I ask something. I've been having trouble with this problem code. I really need to make my own word translator but the problem is when the translation_word doesn't have the key and values.
The code:
enter = input("Please Enter the word/s: ")
translation_word = {
"ONE": "Uno",
"TWO": "Dos",
"THREE":"Tres",
"FOUR": "Kwatro",
"FIVE": "Singko",
"SIX": "Sais",
"SEVEN": "Syete",
"EIGHT": "Otso",
"NINE": "Nwebe",
"TEN": "Gis",
enter.upper(): enter
}
Keys = enter.upper().split()
print(Keys)
# get translation and join the translated words into a single string
Values = ' '.join(translation_word.get(str(Key)) for Key in Keys)
print(Values)
expected result:
input: one two three eleven
output: Uno Dos Tres eleven
The code actually worked if I tried the input one two three but when I added something without in KEY&VALUE it always says error.
Solution 1:[1]
you can use a simple if statement to check if the key exists and print something if it doesn’t. For example:
if key in translation_word:
Values = ''.join(translation_word.get(str(Key)) for Key in Keys)
print(Values)
else:
print("This word can't be translated, please enter a different word")
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 | futuref |
