Python - Replacing words in a string with entries from a dictionary
11,709
Solution 1
Different approach
def replace_words(s, words):
for k, v in words.iteritems():
s = s.replace(k, v)
return s
s = 'hello world'
dictionary = {"hello": "foo", "world": "bar"}
print replace_words(s, dictionary)
Solution 2
The cleanest method is to use dict.get
to fallback to the word itself if the word is not in the dictionary:
' '.join([dictionary.get(word,word) for word in 'hello world'.split()])
Solution 3
This works in Python 2.x:
dictionary = {"hello": "foo", "world": "bar"}
inp = raw_input(":")
for key in inp.split():
try:
print dictionary[key],
except KeyError:
continue
However, if you are on Python 3.x, you will want this:
dictionary = {"hello": "foo", "world": "bar"}
inp = input(":")
for key in inp.split():
try:
print(dictionary[key], end="")
except KeyError:
continue
Related videos on Youtube
Author by
wakkydude
Updated on June 04, 2022Comments
-
wakkydude almost 2 years
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"?
-
Admin over 10 yearsTip: Whenever you use
str.join
, use a list comprehension over a generator expression. Reference: stackoverflow.com/a/9061024/2555451 -
roippi over 10 years@iCodez yeah, I always forget that one. Thanks.
-
wakkydude over 10 yearsCan you use "k" and "v" anywhere in python to represent keys and values? If not, where in this code is it defined that k is a key and v is a value for dictionaries?
-
Wooble over 10 years@wakkydude the "for k, v in ..." bit unpacks the tuples returned by iteritems() into those names. You can call them anything you want, but
k
andv
are typical names. -
Guy Markman over 2 yearsIn python 3, it's words.items() instead of words.iteritems()