什么是在python中处理Keyerror Exception的最佳解决方案

时间:2020-04-18 18:15:40

标签: python keyerror

我有一个简单的课,如下所示:

class Test(object):
    def __init__(self):
        first_dict :  {'author': 'Author', 'status': 'Status'}
        second_dict :  {'Author': 'owner', 'Status': 'current-status'}
        third_dict :  {'owner': 'author', 'current-status': 'status'}
obj = Test()

我想处理我的代码是否要使用错误的密钥访问任何词典,如下所示。

obj.second_dict['some_wrong_key']

请注意,second_dict依赖于1st,third_dict依赖于2nd。

1 个答案:

答案 0 :(得分:0)

您可以使用get功能。如果找不到None,它将返回key。另外,它带有一个可选参数,如果找不到key,则会返回该参数。

obj.second_dict.get('some_wrong_key')  # returns None (no error)
obj.second_dict.get('some_wrong_key', "I'm missing here")  # returns "I'm missing here"