I have a dictionary that has values sometimes as strings, and sometimes as a functions. For the values that are functions is there a way to execute the function without explicitly typing ()
when the key is accessed?
Example:
d = {1: "A", 2: "B", 3: fn_1}
d[3]() # To run function
I want:
d = {1: "A", 2: "B", 3: magic(fn_1)}
d[3] # To run function
You just have to use dict. values() . This will return a list containing all the values of your dictionary, without having to specify any key.
Explanation: The values of a dictionary can be accessed using keys but the keys of a dictionary can't be accessed using values.
Given a dictionary, assign its keys as function calls. Case 1 : Without Params. The way that is employed to achieve this task is that, function name is kept as dictionary values, and while calling with keys, brackets '()' are added.
The well-known, or I should say the traditional way to access a value in a dictionary is by referring to its key name, inside a square bracket. Notice that when you want to access the value of the key that doesn't exist in the dictionary will result in a KeyError.
Another possible solution, is to create a custom dictionary object that implements this behavior:
>>> class CallableDict(dict):
... def __getitem__(self, key):
... val = super().__getitem__(key)
... if callable(val):
... return val()
... return val
...
>>>
>>> d = CallableDict({1: "A", 2: "B", 3: lambda: print('run')})
>>> d[1]
'A'
>>> d[3]
run
A perhaps more idiomatic solution would be to use try/except
:
def __getitem__(self, key):
val = super().__getitem__(key)
try:
return val()
except TypeError:
return val
Note however the method above is really for completness. I would not reccomend using it. As pointed out in the comments, it would mask TypeError
's raised by the function. You could test the exact content of TypeError
, but at that point, you'd be better of using the LBYL style.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With