Dictionary that uses regular expressions

Terry Reedy tjreedy at udel.edu
Thu Aug 21 07:17:25 CEST 2003

"Erik Lechak" <prochak at netzero.net> wrote in message
news:1f0bdf30.0308202049.7d251469 at posting.google.com...
> Hello all,
> I wrote the code below.  It is simply a dictionary that uses regular
> expressions to match keys.  A quick look at _test() will give you an
> example.
> Is there a module that already does this?

Not that I know of

>  Is there a way and would it
> be better to use list comprehension? (using python 2.3)

List comp builds a list.  Your __getitem__(s,key) code builds an
ReDict, not a list.  If you extended your initializer to initialize
from a list of items (by passing the list of items on to
dict.__init__), then you could build such a list with a l.c. and
initialize your return ReDict from that.  IE (untested, obviously, and
it's late...)

return ReDict( [item for item in self.items if
re.search(key,item[0]) ] )

If you were always (or even almost always) matching by re's, you might
as well just use a list of items (key,value).  If you really must mix
normal and re retrieval, but only after the dict is built and stable,
then keeping items() as an attribute rather than re-extracting it for
each re access would be faster.

Terry J. Reedy

More information about the Python-list mailing list