Dictionary lookup with regular expression as key

I just remembered that I was meant to post that thing here, too. Problem is the following: you want to retrieve all values of a python dictionary whose keys match a certain regular expression. Solution: Just make a custom dictionary class derived from the builtin one:

class redict(dict):
    def __init__(self, d):
        dict.__init__(self, d)

    def __getitem__(self, regex):
        r = re.compile(regex)
        mkeys = filter(r.match, self.keys())
        for i in mkeys:
                yield dict.__getitem__(self, i)

With this you can do the following:


>>> keys = ["a", "b", "c", "ab", "ce", "de"]
>>> vals = range(0,len(keys))
>>> red = redict(zip(keys, vals))
>>> for i in red[r"^.e$"]:
...     print i
...
5
4
>>>

Tags: , ,

One Response to “Dictionary lookup with regular expression as key”

  1. GeorgePap Says:

    very helpful, thanks

Leave a Reply