I've got this code that translates a string (that starts out as a list) using a dictionary. I wanted the code to translate the string, then un-translate it back to the original.
This is the code that I've got so far:
words = ['Abra', ' ', 'cadabra', '!']
clues = {'A':'Z', 'a':'z', 'b':'y', 'c':'x'}
def converter(words, clues):
words = ''.join(words)
for item in words:
if item in clues.keys():
words = words.replace(item, clues[item])
return words
def reversal(clues):
clues = {v: k for k, v in clues.items()}
print(clues)
x = converter(words, clues)
print(x)
reversal(clues)
x = converter(words, clues)
print(x)
Only, this will print "Zyrz xzdzyrz!" "Zyrz xdzyrz!" I'm not sure why it's not printing: "Zyrz xzdzyrz!" "Abra cadabra!"
Is there an error in my code that is causing it to act this way? I checked clues and it IS reversed properly after it goes through the function. What am I doing wrong?
Looks like you're trying to do a dictionary operation in place within a function. Your function needs to return the reversed version of the dictionary which you then need to pick up in your main:
# Your stuff here
def reversal(clues):
return {v: k for k, v in clues.items()}
x = converter(words, clues)
print(x)
clues_reversed = reversal(clues)
x = converter(words, clues_reversed)
print(x)