RF_956
RF_956

Reputation: 341

How to use regular expression as keys in a dictionary, and how do you access using it?

I have a dictionary with a tuple as keys. Inside the tuple is a number and regular expression. The tuple as key correspond to a any value. I wanted to access the value using the tuple (i.e. regular expression) as keys. For example,

import re

t_dict = dict()
t[(1, r"[0-9]+")] = "Hello world!"
t[(2, r"[a-z]+")] = "Hi!"

Am I doing the right thing in putting a regular expression on it? If not, how do you put a regular expression on it?

Next is I want to get the values in the dictionary using the keys. For example, I want to do it this way.

print t[(1, '99')] # this should print "Hello world!"
print t[(2, 'hey')] # this should print "Hi!"

Upvotes: 0

Views: 551

Answers (1)

ffledgling
ffledgling

Reputation: 12140

To do what you want, you can subclass the builtin dictionary, then overwrite it's __getitem__ method to have the kind of lookup you want.

The problem with this approach is that you will not be able to reproduce the O(1) lookup of an actual dictionary, since Python's inbuilt hash function doesn't understand regexes (and I don't know of any hash that does).

There is no easy way to have an O(1) (constant time) reverse lookup to find which regular expression matches a string. You cannot know which whether a regular expression matches a string unless you've actually tried it.

Upvotes: 1

Related Questions