Regular expression as dictionary key?

Brett Smith bcsmit1 at engr.uky.edu
Mon Dec 3 15:14:22 EST 2001


Luke <LLoeffler at home.com> wrote in message news:<3C0B408C.8030908 at home.com>...
> Cool, but still a linear search.  Plus it short circuits.

This takes care of the latter problem, returning a RegexDict of key/value
pairs if the given regexp matches more than one key. Otherwise, it returns
the value of the sole match.

Hmmm. Do you think that's the proper behavior? Or should a 1-match regexp
also return a RegexDict? Or should a multiple-match regexp return only a
list of values?

This is still incomplete; a complete implementation would need a rewrite of
other methods, such as haskey().

class RegexDict(UserDict):
    """A dictionary that supports regular expressions to get at
    a key.  Response to a post on c.l.py."""
    def __getitem__(self, key):
        if self.data.has_key(key): return self.data[key]
        regex = key
        if isinstance(key, StringType):
            regex = re.compile(key)
        result = RegexDict({})
        for k in self.data.keys():
            if regex.search(k):
                result[k] = self.data[k]
        if len(result) > 1:
            return result
        elif len(result) == 1:
            return result.values()[0]
        else:
            raise KeyError, key

--
-- Brett Smith



More information about the Python-list mailing list