简体   繁体   中英

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM