2013-03-10 101 views
0

如何搜索一個key的字典是否存在或是否存在並打印它的值?在python中搜索一個字典鍵

wordsCounts = {('the','computer'): 2 , ('computer','science'): 3 , ('math','lecture'): 4, ('lecture','day'): 2} 

所以,我想搜索一下('math','lecture')是否存在與否?

pair = ['computer','science'] 
for k in wordscount.keys(): 
    if wordscount[k] == pair: 
     print wordscount[v] 

那麼結果將是一個列表('computer','science'): 3

回答

5

只是測試,如果對的元組存在:

if tuple(pair) in wordscount: 
    print wordscount[tuple(pair)] 

有通過在所有的鍵無需環路字典;一個python字典在找到匹配鍵的時候會更有效率,如果你只是給它鍵值,但它必須是相同的類型。你的字典鍵是元組,因此在搜索時請使用元組鍵。

事實上,在python字典中,列表不允許作爲鍵,因爲它們是可變的;如果密鑰本身可以更改,則無法準確搜索密鑰。

+0

爲什麼不只是創建一個元組呢? '對=('電腦','科學')' – 2013-03-10 14:49:50

+0

@MarkusMeskanen:我假設用戶從這裏的其他地方有一個列表。 – 2013-03-10 14:50:26

+0

@MartijnPieters:Pythonic的方法是嘗試訪問所需的元素,並捕獲拋出的異常,如果它不存在。 – rburny 2013-03-10 14:52:52

0

首先,你可能想知道爲什麼它不工作..

for k in wordscount.keys(): 
    if wordscount[k] == pair: 

wordscount.keys()將返回元組和下一行的名單是字典wordsCount的值進行比較,以列表「對。 解決方案是

for k in wordscount.keys(): 
    if k == tuple(pair): 
     print workscount[k] 
+0

謝謝bgporter!我正要這麼做:) – Arovit 2013-03-10 15:00:27