2

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"?

wakkydude
  • 31
  • 1
  • 1
  • 2

4 Answers4

7

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)
Andrew Walker
  • 40,984
  • 8
  • 62
  • 84
  • Can 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? – wakkydude Dec 10 '13 at 19:11
  • 1
    @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` and `v` are typical names. – Wooble Dec 10 '13 at 19:26
  • In python 3, it's words.items() instead of words.iteritems() – Guy Markman Dec 11 '21 at 13:45
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()])
roippi
  • 25,533
  • 4
  • 48
  • 73
  • Tip: Whenever you use `str.join`, use a list comprehension over a generator expression. Reference: http://stackoverflow.com/a/9061024/2555451 –  Dec 10 '13 at 19:05
  • @iCodez yeah, I always forget that one. Thanks. – roippi Dec 10 '13 at 19:05
1

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
0

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.

new_str = ""
words = your_input.split(" ")
for i in range(0, len(words)):
  word = words[i]
  if word in dictionary:
    words[i] = dictionary[word]

Now you can do something with your final list of words. For example, join them together separated by spaces

" ".join(words)
MxLDevs
  • 19,048
  • 36
  • 123
  • 194