Dictionary with regular expression

import re

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

  def __getitem__(self, key):
    try:
      return super(RegexDict, self).__getitem__(key)
    except KeyError as ex:
      for kkey, value in self.iteritems():
        if re.match(kkey, str(key)):
          return value
      raise ex

usage:

z = RegexDict({
  'a': 100,
  '\d+': 300,
  1: 3
  })
z['re#\d+'] = 100

print z['a']
print z[2]
print z['a']
print z[1]
print z['re#200']

results:

100
300
3
100

No comments: