Dictionary that uses regular expressions

Erik Lechak prochak at netzero.net
Thu Aug 21 06:49:51 CEST 2003

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

Is there a module that already does this?  Is there a way and would it
be better to use list comprehension? (using python 2.3)

Just looking for a better or more pythonic way to do it.

import re

class ReDict(dict):
    A dictionary that uses regular expressions keys
       if the redict finds more than one key that matches the re it
       returns a redict of all of the matching keys
    def __init__(self):

    def reOn(self):
        turn regular expression matching on
    def reOff(self):
        turn regular expression matching off
    def __getitem__(self,key):
        if self.re ==1:
            temp = ReDict()
            for item in self.items():
                if re.search(key,item[0]):  #line match
            if len(temp)==1:
                return temp.values()[0]
            return temp
            return dict.__getitem__(self,key)

def _test():
    d['call jan 5.0']=1
    d['call jan 7.5']=1.5
    d['put jan 7.5']=7.2
    d['call feb 5.0']=2
    d['call feb 7.5']=2.5
    d['put feb 7.5']=6.8    

    d['call mar 5.0']=3
    d['call mar 7.5']=3.5
    d['put mar 7.5']=4
    d['call apr 5.0']=4
    d['call apr 7.5']=4.5
    d['put apr 7.5']=6.2
    d['call may 5.0']=5
    d['call may 7.5']=5.5
    d['put may 7.5']=4.9
    print d['price'] #prints the price
    print d['call']['may']['7.5'] # prints individual value
    print d['call'] #returns a redict of all calls
    print d['put']  #returns a redict of all puts
    print d['may'] #returns a redict of all options in may


Erik Lechak

More information about the Python-list mailing list