Arethmetic Arranger; regex as dict key

Hi, I’ve coded a dictionary with 2 lambda functions in, which do the calculations for this function. To my surprise, it worked! But then I tried adding a third pair to the dict, to handle errors. Basically its (supposed to be) a regex statement that looks for all characters that aren’t + or -; Unfortunately I get ‘invalid syntax’ pointing at the ^ in the regex.

import re
inpt = "5870 n 2309"
lst = inpt.split()
calc = {'+': lambda x, y: x + y, '-': lambda x, y: x - y,[^+-]*: print(error) }
ans = (calc[lst[1]](int(lst[0]),int(lst[2])))

Is using regex as a dictionary key not allowed? Or am I just doing it wrong? I tried putting the regex in quotes; didn’t change anything…


[^+-]* can’t be a dictionary key, but a string with it - '[^+-]*' should be okay. What error did you get?

First off, a dictionairy key must be an immutable object - numbers or strings.
Second, the key is nothing but a lookup. You cannot put a calculation there. Especially as you realized you need to import the RegEx library, but you aren’t using it - that’s weird, isn’t it?

Anyway, what you try to do MIGHT work with a new feature in Python called “pattern matching”. However it’s so new, I don’t actually know if it’s already released or just announced. It’s the Python version for switch-case and you’d need to look that up yourself ^^°

So the go-to strategy would be to do a if-in-else for the operator and print the error in the else-branch. Or to use the .get() method on the dictionairy and return the error as default-value.

Makes sense, I thought I was pushing it a bit trying to use regex there, it didn’t feel quite right. Using ‘.get()’ makes sense, I’ll try that. I did import re, just forgot to c&p it in here. Pattern matching sounds great, but I’m running python 3.8, so its not going to be there. Sounds like a good idea though. Thanks again.

It was just the invalid syntax.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.