-1
translator = input("Enter a japanese word: ")

japanese_to_english = {
    "Konichiwa": "Hello",
    "baka": "fool",
    "gomen": "sorry",
    "sugoi": "awesome",
}

from the code given above, when the user types a word which is inside the dictionary.. I want it to replace the words.. it there any short way of doing this .. Please let me know... Thank you!

dspencer
  • 4,297
  • 4
  • 22
  • 43
  • 1
    What do yo mean by replace the word? You want to replace the `key` or `value`. Where is the code that you had tried? – Prudhvi Apr 17 '20 at 06:02
  • Idk how to do it so ya.. when I say replace I mean..if I type baka in the terminal it should show up as fool – Preciousツ Apr 17 '20 at 06:04
  • Does my answer answers your problem ? Or it is something else ? – azro Apr 17 '20 at 06:05
  • @Preciousツ my code helps in multiple words – Joshua Varghese Apr 17 '20 at 06:10
  • Does this answer your question? [Accessing elements of Python dictionary by index](https://stackoverflow.com/questions/5404665/accessing-elements-of-python-dictionary-by-index) – MrProgrammer Apr 17 '20 at 06:12
  • @Joshua Varghese yea thank you for your help! I really appreciate the fact that you helped me out but since I just started ... I dont get the code so...ya.. Thank you for helping tho! :) – Preciousツ Apr 17 '20 at 06:19

2 Answers2

1

To access a value from a key, the notation is mydict[mykey] or mydict.get(mykey)

translator = input("Enter a japanese word: ")

japanese_to_english = {...}

english_word = japanese_to_english[translator]       # raise error if word not in dict
english_word = japanese_to_english.get("translator") # return None if word not in dict
azro
  • 53,056
  • 7
  • 34
  • 70
  • @Preciousツ You may leanr more python before trying to use it, because this is very basic of dictionnaries ;) You can think about vote up/accept the answer now ;) – azro Apr 17 '20 at 06:10
  • yea..just started to learn for fun because of the whole situation rn...still learing...thanks!! :) – Preciousツ Apr 17 '20 at 06:16
0

Try:

translated = ' '.join(japanese_to_english[i] if i in japanese_to_english else i for i in translator.split())

Here, we split the input by space, checks them if they are inside the dict, if so replaces it. If not found the word is not replaced.
So if you input:

Konichiwa i am gomen

you get:

'Hello i am sorry'
Joshua Varghese
  • 5,082
  • 1
  • 13
  • 34
  • 2
    An answer without details values nothing, you can't just tell the OP "Do this" without explaining how it solves its problem and what it does – azro Apr 17 '20 at 06:04
  • I did not downvote, maybe the problem was that the OP did not talked about multiples words, don't know – azro Apr 17 '20 at 06:09