我有一个简单的课,如下所示:
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。
答案 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"