I wrote a program that shifts letters in a string and returns a dictionary. It works, unless the letter 'w' is within the string. Does anyone know why this happens? This is my code:
def buildCoder(shift):
import string
impStr = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
resultDict = {}
lowerValues = dict()
for index, letter in enumerate(string.ascii_lowercase):
lowerValues[letter] = index + 1
upperValues = dict()
for index, letter in enumerate(string.ascii_uppercase):
upperValues[letter] = index + 1
inv_lowerValues = {v:k for k, v in lowerValues.items()}
inv_upperValues = {v:k for k, v in upperValues.items()}
for char in impStr:
if char in string.ascii_lowercase:
value = lowerValues[char]
value += shift
if value <= 25:
resultDict[char] = inv_lowerValues[value]
else:
value = abs(26-value)
resultDict[char] = inv_lowerValues[value]
elif char in string.ascii_uppercase:
value = upperValues[char]
value += shift
if value <= 25:
resultDict[char] = inv_upperValues[value]
else:
value = abs(26-value)
resultDict[char] = inv_upperValues[value]
return resultDict
This is the error I get (if 'w' is included in impStr):
KeyError Traceback (most recent call last)
<ipython-input-117-0f4ac72e3c63> in <module>()
----> 1 buildCoder(3)
/var/folders/CV/CVkEwo3TGuu4+2cStWCRyE+++TQ/-Tmp-/tmpMr_sV1.py in buildCoder(shift)
KeyError: 0
I also saw this error:
Traceback (most recent call last):
File "submission.py", line 24, in buildCoder
resultDict[char] = inv_lowerValues[value]
KeyError: 0
*** ERROR: Expected to find a dictionary in the line:
Traceback (most recent call last):
File "submission.py", line 24, in buildCoder
resultDict[char] = inv_lowerValues[value]
KeyError: 0
***
0, notw. My guess isvalue = abs(26-value)gets triggered ifvalue == 26, which means it's checkinginv_lowerValues[0]which doesn't exist.