Using a dictionary to create Caesar Cipher, outputting only one item
Solution 1:
You want to build the dictionary first. When you're done, return the dictionary you just built.
def build_cipher(shift):
cipher = dict()
for i in range(0, 26):
letter = alphabet[i]
shiftedletter = alphabet[(i - shift) % 26]
cipher[letter] = shiftedletter
return cipher
Or, as a comprehension:
def build_cipher(shift):
return {alphabet[i]: alphabet[(i - shift) % 26] for i in range(0, 26)}
Solution 2:
As an alternative, you can use str.maketrans()
to make a translation table t
with any shift value:
def make_table(alpha, shift):
k = shift % len(alpha)
return str.maketrans(alpha, alpha[k:] + alpha[:k])
Then use s.translate(t)
to translate any string s
:
In [1]: s = "hello world"
In [2]: alpha = "abcdefghijklmnopqrstuvwxyz"
In [3]: t = make_table(alpha, 13)
In [4]: s.translate(t)
Out[4]: 'uryyb jbeyq'
In [5]: t = make_table(alpha, -42)
In [8]: s.translate(t)
Out[8]: 'rovvy gybvn'