0

My code...

sentence = "hello world helloworld"

dictionary = {"hello": "1", "world": "2", "helloworld": "3"}

for key in dictionary:
    sentence = sentence.replace(key, dictionary[key])

print(sentence)

What I want it to do...

1 2 3

What it actually does...

1 2 12
2
  • Please specify, if your sentence only contains words from the dictionary, or if other words are possible. Also in the current form you will get an error: AttributeError: 'list' object has no attribute 'replace' Commented May 3, 2017 at 10:39
  • My sentence will only contain words from the dictionary. Commented May 3, 2017 at 10:44

3 Answers 3

2

Try this:

sentence = "hello world helloworld"
sentence = sentence.split()

dictionary = {"hello": "1", "world": "2", "helloworld": "3"}

print ' '.join(map(lambda x: dictionary.get(x) or x , sentence))
Sign up to request clarification or add additional context in comments.

5 Comments

This works if any possible word in sentence actually exists in the dictionary.
Really like the or-approach. +1
dict.get(x) or x could be made slightly shorter using the default argument: dict.get(x, x)
@HannesOvrén, I do agree that it is shorter, but it's confusing at the same time, right?
Yeah, I'm not convinced it is necessarily better.
1

If your sentence can contain words not in your dictionary, which should be returned unchanged, try this approach:

sentence = "hello world helloworld missing words"
sentence = sentence.split()

dictionary = {"hello": "1", "world": "2", "helloworld": "3"}

for i, word in enumerate(sentence):
    sentence[i] = dictionary[word] if word in dictionary else word

print(" ".join(sentence))

Comments

0

The order of the replacements is important. In your case:

  • when hello is replaced : "1 world 1world"
  • when world is first replace : "1 2 12"

To avoid it iterate the keys by order of their length. from the longest to shorter.

for key in dictionary.keys().sort( lambda aa,bb: len(aa) - len(bb) ):
    sentence = sentence.replace(key, dictionary[key])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.