2017-01-02 121 views
0

所以我有一本字典,看起來是這樣的:問題與Python循環處理

data = {'student': {'gradeone': {'subject1': {'result': {'marks': '91', 'remarks': 'pass'}, 'id': 'RA110'}, 'studious': Yes, 'Defaulter': [], 'overall': '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返回一個錯誤,說「無類型對象不可迭代」

您能否幫助適當地修改函數,以便當「學生」鍵爲none時,該函數適當地返回false而不返回上述錯誤?應該使用try-catch嗎?

+2

您的縮進很差(實際上是錯誤的),這隱藏了只有2個if語句纔有3個返回語句的事實。我不明白你的目的是否足夠確定哪些退貨聲明(如果有的話)是多餘的。清理你的代碼,看看是否能更容易地找到你的錯誤。 –

+0

您應該顯示整個函數,以便我們可以瞭解返回語句所屬的位置。 –

回答

7

你可以簡單地這樣做:

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

'除了(KeyError,TypeError):'實際上會工作,如果其中一個條目存在,但包含None而不是字典。 – jsbueno

+0

@jsbueno啊!接得好。我會編輯。 –

2

'gradeone' in data['student']引起的問題:如果data['student']None,運營商in不適用。