Reputation: 1279
I am a beginner to list comprehension and am having trouble figuring something out. According to examples I have looked at on stackoverflow and other sites, I have a list comprehension that seems like it should work, but I have not been able to accomplish the desired output, as I have been unable to figure out the correct syntax for what I want to accomplish.
Given a string, I would like my function to return the string with the alpha characters replaced with the value associated with a key in the provided dictionary. For that task my list comprehension works, but I also need any characters and spaces to stay intact (no change).
Here is what I have tried:
#random dictionary for my example
d = {'a': 'b', 'c': 'i', 'b': 'a', 'e': 'j', 'd': 'm', 'g': 'q','f': 'l',
'i': 'c', 'h': 'w', 'k': 'r', 'j': 'e', 'm': 'd','l': 'f', 'o': 'v',
'n': 's', 'q': 'g', 'p': 't', 's': 'n','r': 'k', 'u': 'x', 't': 'p',
'w': 'h', 'v': 'o', 'y': 'z', 'x': 'u', 'z': 'y'}
def cipher(message):
word = list(message)
word = [v for x in word for k,v in d.iteritems() if x == k]
#word = [v for x in word for k,v in d.iteritems() if x == k else x for x in word]
return "".join(word)
print cipher("that tree is far away!")
This returns my string with the alpha characters correctly changed, but with no spaces and with no ! mark. From further research, that lead me to try the else statement I have in the list comprehension that is commented out in my code example, but that doesn't work.
Can I edit my syntax or can I not accomplish what I am trying to do using list comprehension?
To further clarify:
I am receiving this output: pwbppkjjcnlbkbhbz
I want this output: pwbp pkjj cn lbk bhbz!
Upvotes: 0
Views: 184
Reputation: 78556
Your current approach filters out all characters that are not in the dictionary viz. whitespace and the exclamation.
You could use the .get
method of the dictionary instead to fetch replacements and return the original character when a replacement character does not exist in your mapping:
def decipher(message):
return "".join(d.get(x, x) for x in message)
print decipher("that tree is far away!")
#pwbp pkjj cn lbk bhbz!
Note that strings are iterable so word = list(message)
is really not necessary and can be dropped.
On a another note, the name of the function probably reads better as cipher
Upvotes: 6