2016-02-11 206 views
0

我想從字典中使用另一個鍵的值中刪除鍵。密鑰存在,它表示它存在於我鍵入value in dict.keys()時,但當我試圖刪除它時,我收到了錯誤信息。Python中的KeyError當從字典中刪除一個鍵時,但存在鍵

def remove_duplicate_length(choices): 
    print choices 
    print choices['scheme'] 
    print type(choices['scheme']) 
    print choices['scheme'] in choices.keys() 
    print 'AABB' in choices.keys() 
    scheme = choices['scheme'] 
    print type(scheme) 
    del choices[scheme] 

打印此:

{'ABAB': '2', 'AABB': '6', 'scheme': 'AABB', 'authors': ['Bukowski']} 
AABB 
<type 'str'> 
True 
True 
<type 'str'> 
None 

,並試圖嘗試直接打印結果時引用return語句,或keyerror: AABB的結果時給TypeError: 'NoneType' object has no attribute '__getitem__'

我打印的結果是這樣的:

@route('/', method='POST') 
def getUserChoice(): 
    user_selection = parse_data(request.body.read()) 
    print user_selection 
+0

你打算如何打印結果? – karthikr

+0

'del choices ['scheme']' – user2255757

+2

'None'是因爲'del'沒有給你返回類型。如果你檢查'選擇',你會發現這個鍵不再是字典 – karthikr

回答

0

Python的dict有一個非常util的方法,get。假設你的字典可能有或沒有一個關鍵字。您可以使用get來檢索它的密鑰或其他內容,然後您可以檢查結果是否符合您的條件。

>>> mydict = {'name': 'Jhon', 'age': 2} 
>>> mydict.get('name') 
Jhon 
>>> mydict.get('lastname', 'Not found') 
Not found 

在你的方法中,你可以檢查key是否存在,然後刪除它。

... 
scheme = choices.get('scheme', None) 
print type(scheme) 
if scheme: 
    del choices[scheme] 
相關問題