11

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?

sth
  • 222,467
  • 53
  • 283
  • 367
Sushisource
  • 611
  • 6
  • 17

2 Answers2

21
[(k, v) for (k, v) in D.iteritems() if 'Light' in k]
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • Ah, I was thinking of something like this, I just wouldn't have expressed it so elegantly. I secretly was hoping there might be some sneaky more efficient solution though :) – Sushisource Jul 15 '10 at 05:08
  • If performance is critical, memory is cheap, and the record collection changes only rarely, you could build another "index" dict with individual words as keys and list-of-albums-containing-that-word as values. Unless you're doing a lot of lookups and have a truly huge record collection it's probably not worthwhile. – Russell Borogove Jul 15 '10 at 07:26
0

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'
hobs
  • 18,473
  • 10
  • 83
  • 106