-1

How to change the string to result?

string = 'John and Mary are good friends'
d = {'John': 'Sam', 'Mary': 'Ann', 'are': 'are not'}

result = 'Sam and Ann are not good friends'

Thank you.

John
  • 691
  • 1
  • 7
  • 20
  • Is a list of possible names supplied? I see you have 'Sam' and 'Ann' in the output, but not the input. This sounds like graph theory. Are you trying to find nodes that aren't directly connected? – catleeball May 25 '19 at 05:46
  • We would like to see your effort in solving the problem next time – cs95 May 25 '19 at 06:03

4 Answers4

5

If keys in dictionary have only one word is possible split, map by get and join back:

a = ' '.join(d.get(x, x) for x in string.split())
print (a)
Sam and Ann are not good friends

If possible multiple words and also is necessary use words boundaries for avoid replace substrings:

import re

string = 'John and Mary are good friends'
d = {'John and': 'Sam with', 'Mary': 'Ann', 'are good': 'are not'}

pat = '|'.join(r"\b{}\b".format(x) for x in d.keys())
a = re.sub(pat, lambda x: d.get(x.group(0)), string)
print (a) 
Sam with Ann are not friends
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
0

You can do it like this:

string = 'John and Mary are good friends'
d = {'John': 'Sam', 'Mary': 'Ann', 'are': 'are not'}

result = string

for key, value in d.items():
    result = result.replace(key, value)

print(result)

output:
Sam and Ann are not good friends
Amir Shabani
  • 3,857
  • 6
  • 30
  • 67
0

1 - Iterate over each word of string.

2 - check if word exists in dictionary keys.

3 - If it does exist append value of that word to result. if it does not, append word to result.

Ash Ishh
  • 551
  • 5
  • 15
0

Basic approach:

  1. split the long string into a list of words
  2. iterate through this list of words; if any word exists as a key in the given dictionary, replace that word with the corresponding value from the dictionary
  3. join the list of words together using space
string = 'John and Mary are good friends'
d = {'John': 'Sam', 'Mary': 'Ann', 'are': 'are not'}

s = string.split()
for i, el in enumerate(s):
    if el in d:
        s[i] = d[el]
print(' '.join(s))
Dino
  • 446
  • 4
  • 12
  • Please don't only post code as an answer, but also provide an explanation what your code does and how it solves the problem of the question. That will make your answer more valuable and is more likely to attract upvotes. – Mark Rotteveel May 25 '19 at 06:29
  • @Mark Rotteveel thanks for the advice - I've updated the answer. – Dino May 25 '19 at 12:55