CodePlorer
CodePlorer

Reputation: 163

Issue with Python Loop handling

So I have a dictionary that looks something like this :

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

For this I wrote the following code which checks for "overall" key and if it is set to "Excellent" function returns 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

But if the data is something like this :

data = {'student' : None }

My function instead of returning False returns an error saying "None Type Object is not iterable"

Can you help modify the function appropriately so that when the "student" key is none, the function returns false appropriately without returning the aforementioned error ? Should a try-catch be used?

Upvotes: 0

Views: 71

Answers (2)

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 96349

You can simply do something like:

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

Upvotes: 7

DYZ
DYZ

Reputation: 57125

'gradeone' in data['student'] is causing the problem: if data['student'] is None, the operator in is not applicable.

Upvotes: 2

Related Questions