user7435238
user7435238

Reputation:

How do I replace a string with values from a dictionary? Python

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

Answers (3)

Christian König
Christian König

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

Ahasanul Haque
Ahasanul Haque

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

napuzba
napuzba

Reputation: 6288

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])

Upvotes: 0

Related Questions