Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a function as dictionary key

Tags:

python

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"}
like image 874
ViralSpiral Avatar asked Jan 13 '15 05:01

ViralSpiral


People also ask

Can a function be a key in a dictionary Python?

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.

Can a function be a dictionary value?

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.

How do you apply a function to a dictionary?

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.

What does dictionary key function do?

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.


1 Answers

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}
like image 138
101 Avatar answered Oct 09 '22 11:10

101