Python: Finding a (string) key in a dictionary that contains a substring
In my script I build a dictionary of keys(albums) mapped to artists(values) so that I can do a quick lookup of what artists made what albums. However, I want the user to be able to find all albums which contain a substring. For example a search on "Light" should return
[Light Chasers] = Cloud Cult
and also [Nigh开发者_StackOverflow中文版t Light] = Au Revoir Simone
What's the best way to do this? Should I even be using a dictionary?
[(k, v) for (k, v) in D.iteritems() if 'Light' in k]
If you ever just need the first album containing the text, here's a fast way:
try:
return ('[%s] = %s' % (k, D.get(k)) for k in D if search_string.lower().strip() in k.lower()).next()
except StopIteration:
return 'No matches found'
精彩评论