1
>>> d = {'a': 1, 'b': 2}
>>> list(map(lambda x: x[0] * x[1], d.items()))
['a', 'bb']

I'd rather be able to name my variables in my function, but this

>>> list(map(lambda k, v: k * v, d.items()))
TypeError: <lambda>() missing 1 required positional argument: 'v'

obviously won't work since map feeds single inputs to the function.

What I've done for myself is write a decorator (here simplified);

def asterisk(func):
    def _func(single_input):
        return func(*single_input)
    return _func

that then allows me to do this

>>> list(map(asterisk(lambda k, v: k * v), d.items()))
['a', 'bb']

But I can't help but think I'm missing a simple trick or builtin function here.

thorwhalen
  • 1,920
  • 14
  • 26

1 Answers1

0

You can use a generator expression for list like so:

list(k * v for k, v in d.items())
Rfroes87
  • 668
  • 1
  • 5
  • 15