Can a regular expression be used as a key in a dictionary?
Question: I want to create a dictionary where the keys are regular expressions:

    
    
    d = {'a.*': some_value1, 'b.*': some_value2}
    

Then, when I look into the dictionary:

    
    
    d['apple']
    

I want apple `'apple'` to be matched against the keys which are regular
expressions. If there is a complete match with a key/regular-expression then
the corresponding value should be returned.

For example `'apple'` matches with the regular expression `'a.*'` completely,
and so, `some_value1` should be returned.

Of course, all of this assumes that the regular expression keys do not
conflict (i.e. two keys should not both match the same string exactly). Let's
say I can manually take care of this requirement when building my keys.

Is this possible in Python? If so, it would be quite an elegant and powerful
construct!


Answer: You can use a `re.compile`d pattern object as a dictionary key:

    
    
    >>> import re
    >>> regex = re.compile('a.*')
    >>> d = {regex: 'foo'}
    >>> d[re.compile('a.*')]
    'foo'
    

Note that recompiling the same regex gives you an equal key (the same object,
in fact: `re.compile('a.*') is d.keys()[0]`), so you can get back whatever you
stored against it.

However:

  * As pointed out in the comments, _multiple regular expressions can match the same string_ ; 
  * Dictionaries aren't ordered, so you might get a different matching regex first each time you run the program; and 
  * There's no `O(1)` way to ask a dictionary `{regex: result, ...}` for a `result` value given a string that might match one or more `regex` keys. 

It's therefore difficult to see what utility you'd find for this.

* * *

If you _can_ come up with a way to ensure that no two keys can match the same
string, you could create a
[`MutableMapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.MutableMapping)
subclass that applies this check when you add new keys and implements
`__getitem__` to scan through the key-value pairs and return the first value
where the argument matches the key regex. Again, though, this would be `O(n)`.

