Search code examples
pythondictionarytext

How do I replace letters in text using a dictionary?


I have a dictionary that looks like this:

Letters = {'a': 'z', 'b': 'q', 'm':'j'}

I also have a block of random text.

How do I get replace the letters in my text with the letter from the dictionary. So switch 'a' to 'z' and 'b' to 'q'.

What I've done so far is returning the wrong output and I can't think of any other way:

splitter = text.split()
res = " ".join(Letters.get(i,i) for i  in text.split())
print(res)

Solution

  • You're iterating over the words in text, not over the letters in the words.

    There's no need to use text.split(). Just iterate over text itself to get the letters. And then join them using an empty string.

    res = "".join(Letters.get(i,i) for i  in text)