mmann1123
mmann1123

Reputation: 5305

map dictionary of function names and arguments

I have to execute a large number of functions, with a variety of different arguments. How can I map a function over a dictionary of functions w/ lists of arguments

Rather than:

a = np.array([1,2,3,4,5,6])

np.mean(a)
np.quantile(a,q=0.5)
np.quantile(a,q=0.5)

Unpack and execute across all combinations in dictionary:

f_dict = { 'maximum':{} ,
          'quantile': [{'q':"0.5"},{'q':'0.95'}]}
 

Upvotes: 0

Views: 964

Answers (1)

Anwarvic
Anwarvic

Reputation: 13022

First of all, I recommend using the actual functions as the keys for the dictionary. Also, I recommend formalizing the dictionary values to be a list of dictionaries.

If you did both of these changes, then you can use something like so:

f_dict = { np.mean:[{}] ,
          np.quantile: [{'q':0.25}, {'q':0.5}]}

print([func(a, **arg) for func, args in f_dict.items() for arg in args])
#[3.5, 2.25, 3.5]

Upvotes: 1

Related Questions