Reputation: 863
I want to change some of the words of my string, S to some others based on the dictionary, D. For example, for the following values of S and D:
S="I don't know, who you are?"
D={"doesn't":"does not","don't":"do not"}
I should get
S="I do not know, who you are?"
To do this, I am writing the following code:
L=str.split(' ')
index = [D[x] if x in D.keys() for x in L]
But this is giving syntax error. Kindly help me in resolving this error so that I am able to get the required output as shown above. If there is an even better solution to this problem, please explain that.
Upvotes: 0
Views: 45
Reputation: 1311
You can check this one liner answer too:
S="I don't know, who you are?"
D={"doesn't":"does not","don't":"do not"}
result = ' '.join(map(lambda x: D[x] if D.get(x) else x, S.split()))
print(result)
Output:
'I do not know, who you are?'
Upvotes: 2
Reputation: 49260
You just need to get the string value if the value is not in the dictionary.
result = ' '.join(D.get(x,x) for x in S.split(' '))
The reason for syntax error with [D[x] if x in D.keys() for x in L]
is that if
needs to go after for
if there is no accompanying else
condition. Look up the syntax in the documentation.
Upvotes: 1