1

As above, I want to use map function to apply a function to a bunch of things and collect results in a list. However, I don't see how can I pass kwargs to that function.

For concreteness:

map(fun, elements)

What about kwargs?

Alex
  • 599
  • 1
  • 5
  • 14

2 Answers2

7

Use a generator expression instead of a map.

(fun(x, **kwargs) for x in elements)

e.g.

reduce(fun(x, **kwargs) for x in elements)

Or if you're going straight to a list, use a list comprehension instead:

[fun(x, **kwargs) for x in elements]
wjandrea
  • 28,235
  • 9
  • 60
  • 81
2

The question is already answered at Python `map` and arguments unpacking

The map does not exactly support named variable, though can handle multiple variable based on position.

Since Python 3 the standard map can list arguments of multi-argument separately

map(fun, listx, listy, listz)

It is though less convenient for variable length list of named variables, especially in presence of **kwargs in the function signature. You can, though, introduce some intermediate function to pack separately positional and named arguments. For one line solution with lambda see Python `map` and arguments unpacking If you are not proficient with lambda, you can go as below

def foldarg(param): 
    return f(param[0], **param[1])
list(map(foldarg, elements))

where elements is something like

[[[1,2], dict(x=3, y=4)],
[[-2,-2], dict(w=3, z=4)]]

For unnamed variables list you can also use itertools.starmap

Serge
  • 3,387
  • 3
  • 16
  • 34