Python循环处理问题

时间:2017-01-02 18:25:16

标签: python dictionary

所以我有一个字典看起来像这样:

data = {'student': {'gradeone': {'subject1': {'result': {'marks': '91', 'remarks': 'pass'}, 'id': 'RA110'}, 'studious': Yes, 'Defaulter': [], 'overall': 'EXCELLENT'}}

为此,我编写了以下代码,用于检查“整体”键,如果设置为“Excellent”,则返回TRUE:

if(data and 'student' in data and
   'gradeone' in data['student'] and
   'overall' in data['student']['gradeone']):
    if(data['student']['gradeone']['overall'] == 'EXCELLENT'):
        return True
    return False
return False

但如果数据是这样的:

data = {'student' : None }

我的函数而不是返回False返回一个错误,说“无类型对象不可迭代”

你能否帮助适当地修改函数,以便当“student”键为none时,函数返回false而不返回上述错误?应该使用try-catch吗?

2 个答案:

答案 0 :(得分:7)

您可以简单地执行以下操作:

def is_excellent(data):
    try:
        return data['student']['gradeone']['overall'] == 'EXCELLENT'
    except (KeyError, TypeError):
        return False

答案 1 :(得分:2)

'gradeone' in data['student']导致问题:如果data['student']None,则运营商in不适用。