如何搜索一个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