On Thu, Oct 06, 2005 at 10:28:23PM -0400, Kent Johnson wrote: >William O'Higgins Witteman wrote: >> I'm trying to traverse a dictionary looking for partial matches of the >> key, and I'm not sure how. Here's a sample dictionary: >> >> dict = {00001234 : value1, 20051234 : value2, 20071234 : value3} >> >> Here's what I'm trying to do: >> >> for key in dict: >> if key == 0000???? or key == 2005????: > > if key.startswith('0000') or key.startswith('2005'):
This is perfect! Where do I read about things like this? I've been spending a bunch of time with the python.org documentation, "A Byte of Python" and "Dive Into Python", but I didn't run across this. >or with a regular expresion: > if re.match('0000|2005', key): This is good too, and it shows me the syntax (which I had trouble with). >> do something with dict[key] >> >> The challenge is that I only care about the first four digits of the key >> for the purpose of this match - is there a way to express this? I could >> probably create a wrapper dictionary using just the first four digits of >> the key as they key, and containing the original key:value pair as a >> list within it, but that seems cumbersome. Any one have a suggestion? > >If you have a *lot* of keys and need more speed, that might be a good >optimization. For a small dict, just use startswith(). Should I compile the regex to further increase the speed? Thanks for the help. -- yours, William
signature.asc
Description: Digital signature
_______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor