I’m new to python and I really like concept of using dictionaries instead of switch/case statements, but there is one problem I can’t figure out
Let’s say we have a ‘pythonic case’ statement
{
'a': somemethod,
'b': othermethod
}['a']()
This works fine, but I can’t figure out how to run some block of code like in other languages like java, something which would look like this
{
'a': { some commands here }
'b': { other commands here that are executed }
}['a']
Maybe lambda could help?
Thank you so much
Dictionary values have to be objects of some kind. This means that you essentially must encapsulate the code you want to run within a function defined elsewhere. You could toy with
exec— you could create a dict of strings, and thenexeca string from the dict, for example — but I wouldn’t recommend it.lambdadoes partially answer your question, butlambdais limited in its applicability; it can only create one-line functions, among other limitations. Still, for very simple functions, it is adequate.The best way to do this with longer blocks of code is simply to define a function or method.