I am trying to make a program that will take an input, look to see if any of these words are a key in a previously defined dictionary, and then replace any found words with their entries. The hard bit is the "looking to see if words are keys". For example, if I'm trying to replace the entries in this dictionary:
dictionary = {"hello": "foo", "world": "bar"}
how can I make it print "foo bar" when given an input "hello world"?
The cleanest method is to use
dict.get
to fallback to the word itself if the word is not in the dictionary:Assuming a "word" is a continuous sequence of characters, you can split your input on spaces, and then for each word, check if it's in the dictionary or not.
Now you can do something with your final list of words. For example, join them together separated by spaces
Different approach
This works in Python 2.x:
However, if you are on Python 3.x, you will want this: