简体   繁体   中英

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 [Night 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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM