In [[Python]], you can use [[Regular Expressions]] to allow for dynamic key lookups in a dictionary. You should almost never want to do this.
```python
table_models = {
"sam-(\w+)-attributeaccount([a-z]+).*": AttributeAccountModel
}
```
And then I use a list comprehension to get all matches (in case there is more than one, but there shouldn’t be), get the first one, and initialize it with the table name:
```python
source_model = [TABLE_MODELS[key] for key in TABLE_MODELS.keys() if re.match(key, source)][0]
```
## Tweet
Want to see some horrific #Python? Did you know you can use regular expressions as keys in Python dictionaries? It's inefficient, has very few use cases, and you probably should never do it, but sometimes we should only think about whether we can, not whether we should
JP gif
```python
from models import AttributeModel, CustomerModel
import re
def get_model(table_name: str):
fuzzy_dict = {
"table-(\w+)-attributes-(\w+)": AttributeModel,
"table-(\w+)-customers-(\w+)": CustomerModel,
}
models = [value for key, value in fuzzy_dict.items() if re.match(key, table_name)]
return models
```
In this snippet, we have a dict that points to some Model objects using keys that are valid regular expressions representing dynamic table names. To get the right model, use dict.items() and check each key for a match. Add the matched key's value to a list or get the 1st match.
This is terrible and largely unnecessary. If you're going to use regular expressions, set up your dict so that the keys are an extractable, differentiating unique pieces of your string (in the example, attributes or customers) and extract that from your input string for the lookup:
```python
from models import AttributeModel, CustomerModel
import re
def get_model(table_name: str):
fuzzy_dict = {
"attributes": AttributeModel,
"customers": CustomerModel,
}
pattern = "table-\w+-(\w+)-\w+"
key = re.match(pattern, table_name).group(1)
model = fuzzy_dict[key]
return model
```
[Tweet](https://twitter.com/KyleStratis/status/1462622730231107584?s=20)
![[post_1 2.png]]
![[post_2 2.png]]