Reputation:
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
Upvotes: 0
Views: 59
Reputation: 3570
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))
Upvotes: 1
Reputation: 11134
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))
Upvotes: 2
Reputation: 6288
The order of the replacements is important. In your case:
hello
is replaced : "1 world 1world"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])
Upvotes: 0