[Tutor] Matching dictionary entries by partial key

Kent Johnson kent37 at tds.net
Fri Oct 7 17:02:01 CEST 2005


William O'Higgins Witteman wrote:
> On Thu, Oct 06, 2005 at 10:28:23PM -0400, Kent Johnson wrote:
>> 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.

Chapter 2 of the Python Library Reference is recommended reading. It documents all the builtin functions (e.g. int(), chr(), enumerate()...) and types (list, dict, str...). In particular section 2.3.6.1 documents string methods such as startswith(). It's worth browsing the table of contents, too - it gives a subject-oriented catalog of all the standard library modules.
http://docs.python.org/lib/builtin.html
http://docs.python.org/lib/string-methods.html

> Should I compile the regex to further increase the speed?

Yes, compile it outside the loop and use the compiled regex for the match:

import re
myRe = re.compile('0000|2005')
for key in dict:
  if myRe.match(key):

BTW dict is a bad name for a dict, it is the name of the actual dict class. In general you should avoid using the names of built-ins as variable names because your variable will shadow the builtin. It's particularly easy to make this mistake with the names 'list', 'dict' and 'file'.

Kent



More information about the Tutor mailing list