如何搜索一個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
爲什麼不只是創建一個元組呢? '對=('電腦','科學')' – 2013-03-10 14:49:50
@MarkusMeskanen:我假設用戶從這裏的其他地方有一個列表。 – 2013-03-10 14:50:26
@MartijnPieters:Pythonic的方法是嘗試訪問所需的元素,並捕獲拋出的異常,如果它不存在。 – rburny 2013-03-10 14:52:52