在python中搜索一个dict键

时间:2013-03-10 14:46:41

标签: 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

2 个答案:

答案 0 :(得分:5)

只测试该对的元组是否存在:

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

无需遍历字典中的所有键;如果你只是给它一个寻找的键,python字典在查找匹配键方面会更有效率,但它必须是相同的类型。您的字典键是元组,因此在搜索时请使用元组键。

事实上,在python词典中,列表不允许作为键,因为它们是可变的;如果可以更改密钥本身,则无法准确搜索密钥。

答案 1 :(得分:0)

首先,你可能想知道为什么它不起作用..

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

wordscount.keys()将返回元组列表,下一行是将dict wordsCount的值与列表'对进行比较。 解决方案是

for k in wordscount.keys():
    if k == tuple(pair):
        print workscount[k]
相关问题