密钥上的Python字典模糊匹配

时间:2015-09-27 13:10:58

标签: python-2.7 dictionary fuzzy-search

我有以下字典:

classes = {'MATH6371': 'Statistics 1', 'COMP7330': 'Database Management', 
'MATH6471': 'Statistics 2','COMP7340': 'Creative Computation' }

我正在尝试在字典键上进行raw_input模糊匹配。例如,如果我输入'math',输出将是Statistics 1和Statistics 2.

我有以下代码,但它只匹配密钥:

def print_courses (raw_input):
    search = raw_input("Type a course ID here:")
    if search in classes:
       print classes.get(search)
    else: 
       print "Sorry, that course doesn't exist, try again"

print_courses(raw_input) 

由于

1 个答案:

答案 0 :(得分:0)

你走了:

>>> search = 'math'
>>> result = [classes[key] for key in classes if search in key.lower()]
['Statistics 2', 'Statistics 1']