Is it considered bad form to use a function as a dictionary key? For example:
def add(a, b):
return a + b
mydict = {add: "hello"}
Dictionaries in Python Almost any type of value can be used as a dictionary key in Python. You can even use built-in objects like types and functions.
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.
You can use the toolz. valmap() function to apply a function to the dictionary's values. Similarly, to apply function to keys of a dictionary, use toolz. keymap() function and to apply function to items of a dictionary, use toolz.
The keys() method returns a view object. The view object contains the keys of the dictionary, as a list. The view object will reflect any changes done to the dictionary, see example below.
Yes, that's perfectly valid. You could for instance use it to store a counter to how many times a function was called:
def hi():
print('hi')
funcs = {hi: 0}
print(funcs)
# {<function hi at 0x10fb39950>: 0}
for func in funcs:
func()
# hi
funcs[func] += 1
print(funcs)
# {<function hi at 0x10fb39950>: 1}
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