-1

I want to replace the following chars with their corresponding values (from the dictionary) in one string:

dictVal = 
{
'a' : 'W',
'p' : 2,
'd' : 5
}

Is there a more elegant way of doing this instead of iterating over ever key of the dictionary?

For example:

input string = 'Please help me'
output string = 'PleWse hel2 me'

Thanks.

Amiclone
  • 388
  • 2
  • 11

1 Answers1

1

You do not need to iterate over the dictionary, you can simply iterate over the string and check if the character is present in the dictionary.

# using d as the variable instead of dict because dict is a keyword
d = {'a': 'W', 'p': 2, 'd': 5}
s = "Please help me"
new_s = ""

for c in s:
    # str(...) because you have numbers as values in the dictionary
    new_s += str(d.get(c, c))

# Output: PleWse hel2 me
print(new_s)

Or, you can use a list comprehension like this:

new_s = ''.join(str(char_mapping.get(c, c)) for c in s)

To understand more on dictionary.get(key, default_value), read here.

Harshal Parekh
  • 5,918
  • 4
  • 21
  • 43
  • 1
    You can also summarise that in a list comprehension, like: `new_s = ''.join(str(char_mapping.get(c, c)) for c in s)` – Elias Mi Jan 09 '20 at 09:47