简体   繁体   English

如何处理 python dict 引发的 TypeError 异常?

[英]How to handle TypeError exception raised by python dict?

I cannot seem to find the error to this code.我似乎找不到此代码的错误。 I keep getting this as my output log.我一直把它作为我的 output 日志。

 STDERR
Traceback (most recent call last):
  File "main.py", line 18, in <module>
    static ("Avoid success at all costs!")
  File "main.py", line 10, in static
    test.assert_equals(rot13(d),sol(d))
  File "/home/codewarrior/solution.py", line 16, in rot13
    newkey = (get_keyA(i)+13)
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

The purpose of this code is to active Rot13, if there is a numerical in there or a space, it'll just leave it as original.此代码的目的是激活 Rot13,如果其中有数字或空格,它将保持原样。

ABC = {1: "A", 2: "B", 3:"C", 4: "D", 5: "E", 6: "F", 7: "G", 8: "H", 9: "I", 10: "J", 11: "K",
       12: "L", 13: "M", 14: "N", 15: "O", 16: "P", 17: "Q", 18: "R", 19: "S",
       20: "T", 21: "U", 22: "V", 23: "W", 24: "X", 25: "Y", 26: "Z"}
abc = {1: "a", 2: "b", 3:"c", 4: "d", 5: "e", 6: "f", 7: "g", 8: "h", 9: "i", 10: "j", 11: "k",
       12: "l", 13: "m", 14: "n", 15: "o", 16: "p", 17: "q", 18: "r", 19: "s",
       20: "t", 21: "u", 22: "v", 23: "w", 24: "x", 25: "y", 26: "z"} 

def rot13(message):
    string = list(message)
    new = ""
    for i in string:
        if (i.isnumeric() == False):
            if (i != " "):
                if (i.islower() == False):
                    newkey = (get_keyA(i)+13)
                    if (newkey > 26):
                        newkey -= 26
                    new += ABC[newkey]
                if (i.islower() == True):
                    newkey = (get_keya(i)+13)
                    if (newkey > 26):
                        newkey -= 26
                    new += abc[newkey] 
            else:
                new += i
        else :
            new += i
    return new
    
    
def get_keyA(val): 
    for key, value in ABC.items(): 
        if val == value: 
            return key 

def get_keya(val): 
    for key, value in abc.items(): 
        if val == value: 
            return key 

Yes, I'm not using encode.是的,我没有使用编码。 I want to try this out without using it.我想在不使用它的情况下尝试一下。 Thank you for reading and thanks for the help!感谢您的阅读并感谢您的帮助!

your functions are written wrongly and non pythonic.您的函数编写错误且非pythonic。 we will fix later.我们稍后会修复。 the bug lays in this line:错误在于这一行:

newkey = (get_keyA(i)+13)

you have called the method with i that doesnot exist in the ABC dict .您使用i调用了ABC dict中不存在的方法。 and you have get None return value from this method.并且您从该方法中获得了None返回值。 hence, None + 13 is something that python cant handle (None + int) .因此, None + 13是 python 无法处理的(None + int) hence the error!因此错误!

Any way this methods are unusable.无论如何,这些方法都是不可用的。 python have built in methods for searching a dict and get the return value: python 内置了搜索字典并获取返回值的方法:

dict.get(key[, value]) 

get(key[, default]) Return the value for key if key is in the dictionary, else default. get(key[, default])如果 key 在字典中,则返回 key 的值,否则返回默认值。 If default is not given, it defaults to None, so that this method never raises a KeyError.如果未给出默认值,则默认为无,因此此方法永远不会引发 KeyError。

Just use it.就用它。 i recommend you to add a try except on this code block(above) Suppose that, if the key i is not exist in the dict , then you can return a default value that suits your program, so th e usage become:我建议您在此代码块上添加尝试除外(上)假设,如果键i不存在于dict中,那么您可以返回适合您的程序的default value ,因此用法变为:

ABC.get(i, <some_default_value>) 

for example: suppose i want to return 0 value if the key i isnot exist in the dict, and then i want to add it to the dict with default value 'foo', so the code becomes:例如:假设我想在字典中不存在键i时返回0值,然后我想将其添加到具有默认值 'foo' 的字典中,因此代码变为:

if not ABC.get(i,0):
    ABC[i] = 'foo'  #add the key i to this dict with the value 'foo'

hence the methods you have wrote ( get_keyA(val) and get_keya(val) ), can be deleted!因此,您编写的方法( get_keyA(val)get_keya(val) )可以删除!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM