2013-03-10 119 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