KeyError python

时间:2014-07-30 18:22:07

标签: python keyerror

我写了一个程序,它在字符串中移动字母并返回字典。它有效,除非这封信是' w'在字符串内。有谁知道为什么会这样?这是我的代码:

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

这是我得到的错误(如果'w'中包含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 

我也看到了这个错误:

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

 ***

3 个答案:

答案 0 :(得分:2)

让我们对你的代码进行一些内省:

lowerValues['w'] == 23
inv_lowerValues[23] == 'w'

# presumably shift == 3

for char in impStr: # when char==w
    if char in string.ascii_lowercase: # it is
        value += shift # 23 + 3 == 26
        if values <= 25 # it's not
        else:
            value = abs(26-value)
            # abs( 26 - 26 ) == 0
            resultDict[char] = inv_lowerValues[value]
            # resultDict['w'] = inv_lowerValues[0]; KeyError

听起来你只是想确保你的班次绕着字母表。那不是abs(26-value),那是(value % 25)+1

答案 1 :(得分:1)

我想,你想写

value = abs(value-25)

而不是

value = abs(26-value)

否则你会得到0值。

答案 2 :(得分:0)

您正在做的更简洁的版本:

import string

def buildCoder(shift):
    alpha = string.ascii_lowercase
    ALPHA = string.ascii_uppercase
    if 0 <= shift < 26:
        unshifted_letters = ALPHA + alpha
        shifted_letters = ALPHA[shift:] + ALPHA[:shift] + alpha[shift:] + alpha[:shift]
        return dict(zip(unshifted_letters, shifted_letters))