0

error showed I am running into a key error while trying to loop through a dictionary. If someone could tell me what I am doing incorrect, it would be helpful. I am trying to make a basic "Caesar cipher", a way to decode messages with an offset of 13. :)

ceasar = {'a':'n', 'b':'o', 'c':'p', 'd':'q', 'e':'r', 'f':'s', 'g':'t', 'h':'u', 'i':'v', 'j':'w', 'k':'x', 'l':'y', 'm':'z', 'n':'a', 'o':'b', 'p':'c', 'q':'d', 'r':'e', 's':'f', 't':'g', 'u':'h', 'v':'i', 'w':'j', 'x':'k', 'y':'l', 'z':'m'}
def ceasar_cipher(encoded):
    encoded = encoded.lower()
    decoded = ""
    for letter in encoded:
        if letter == "?" or letter == "!":
            decoded += letter
    for letter in encoded:
        ceasar[letter] += decoded
        print decoded
  • 1
    What are you calling the function with? I'm assuming there is a space in the words being passed and there is no `' '` in your lookup dict `caesar` - hence the key error. – AChampion Mar 23 '16 at 16:49
  • Try changing your first assignment to `encoded = encoded.lower().strip()` – Bahrom Mar 23 '16 at 16:49
  • fyi, Python includes a [caeser cypher with a key of 13](https://docs.python.org/2/library/codecs.html#python-specific-encodings): `import codecs; print(codecs.encode(message, 'rot_13'))` – RoadieRich Mar 23 '16 at 17:02

2 Answers2

0

Here's another approach, can you give us some sample input and output? What do you want to do with characters that aren't in your caesar dict:

caesar = {'a':'n', 'b':'o', 'c':'p', 'd':'q', 'e':'r', 'f':'s', 'g':'t', 'h':'u', 'i':'v', 'j':'w', 'k':'x', 'l':'y', 'm':'z', 'n':'a', 'o':'b', 'p':'c', 'q':'d', 'r':'e', 's':'f', 't':'g', 'u':'h', 'v':'i', 'w':'j', 'x':'k', 'y':'l', 'z':'m'}

def caesar_cipher(encoded):
    print("".join(caesar.get(letter, letter) for letter in encoded.lower()))
AChampion
  • 29,683
  • 4
  • 59
  • 75
Bahrom
  • 4,752
  • 32
  • 41
0

I think you want

ceasar = {'a':'n', 'b':'o', 'c':'p', 'd':'q', 'e':'r', 'f':'s', 'g':'t', 'h':'u', 'i':'v', 'j':'w', 'k':'x', 'l':'y', 'm':'z', 'n':'a', 'o':'b', 'p':'c', 'q':'d', 'r':'e', 's':'f', 't':'g', 'u':'h', 'v':'i', 'w':'j', 'x':'k', 'y':'l', 'z':'m'}
def ceasar_cipher(encoded):
    encoded = encoded.lower()
    decoded = ""
    for letter in encoded:
        if letter in ceasar.keys():
            decoded += ceasar[letter]
        else:
            decoded += letter
    print decoded

This preserves spaces, punctuation, and any other characters that are not in the translation dict.