Tytire Recubans
Tytire Recubans

Reputation: 997

reduce list of functions with keyword argument on dictionary in python

:)

I want to build a very tiny functional pipeline in my code to reduce a bunch of functions on a single dictionary. Every function does 1 thing, but on different keys, here's a simplified example:

I have this dictionary

d = {"me": "gab", "you": "cita"}

and suppose a silly function like this:

def make_caps(dic, on=None):
    if on is not None:
        to_cap = dic.get(on, None)
    if to_cap is not None:
        dic[on] = to_cap.upper()
    return dic

I would like to have this working:

def reduce_fns_on_dict(fns, dic):
    from functools import reduce
    return reduce(lambda d, f: f(d), fns, dic)

new_dic = reduce_fns_on_dict(fns=[make_caps(on="me"), make_caps(on="you")], 
                             dic=d)

print(new_dic)

on console

{'me': 'GAB', 'you': 'CITA'}

But when I run the above I get:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: make_caps() missing 1 required positional argument: 'dic'

Upvotes: 1

Views: 359

Answers (2)

Laurent H.
Laurent H.

Reputation: 6526

To complete the answer from @FiddleStix, I suggest you to use dictionary comprehension, which I find well-suited in your case:

d = {"me": "gab", "you": "cita"}
new_dic = {k:v.upper() for k,v in d.items() if k in ["me","you"]} 
print(new_dic)
# {'me': 'GAB', 'you': 'CITA'}

Note: you can remove if k in ["me","you"] if you want to capitalize all the values of the dictionary.

Upvotes: 1

FiddleStix
FiddleStix

Reputation: 3721

make_caps(on="me") calls the make_caps function. What you want is a new function which behaves like make_caps(some_arg, on='me'). You can make such a function with functools.partial. The line will look something like fns=[partial(make_caps, on="me")....

EDIT: Alternatively, you could curry the function.

Upvotes: 1

Related Questions