1

Given an input tuple, the goal is to produce a dictionary with some pre-defined keys, e.g. in this case, we have an add_header lambda and use the unpacking inside when calling the function.

>>> z = (2,1)
>>> add_header = lambda x, y: {"EVEN": x, "ODD": y}
>>> add_header(*z)
{'EVEN': 2, 'ODD': 1}

My question is, is there way where the unpacking doesn't need to done when calling the add_header function?

E.g. I can change avoid the lambda and do it in a normal function:

>>> def add_header(input):
...     x, y = input
...     return {"EVEN": x, "ODD":y}
... 
>>> z = (2, 1)
>>> add_header(z)
{'EVEN': 2, 'ODD': 1}

Or I could not use the unpacking and use the index of the tuple, i.e. the z[0] and z[1]:

>>> z = (2, 1)
>>> add_header = lambda z: {"EVEN": z[0], "ODD": z[1]}
>>> add_header(z)
{'EVEN': 2, 'ODD': 1}

But is there some way to:

  • Use the lambda
  • Don't explicitly use the indexing in the tuple
  • Don't unpack with * when calling the add_header() function but it's okay to be inside the lambda function.

and still achieve the same {'EVEN': 2, 'ODD': 1} output given z = (2,1) input?


I know this won't work but does something like this exist?

z = (2,1)
add_header = lambda x, y from *x: {"EVEN": x, "ODD": y}
add_header(z)
alvas
  • 115,346
  • 109
  • 446
  • 738

2 Answers2

2

You can try using dict() with zip():

z = (2, 1)
add_header = lambda tpl: dict(zip(("EVEN", "ODD"), tpl))

print(add_header(z))

Prints:

{'EVEN': 2, 'ODD': 1}
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
1

Don't use a named lambda in the first place. Use the def instead.

P.S. I think there's an argument to be made that lambdas are weak on purpose, to avoid shoehorning them into situations they shouldn't be, like maybe this case, but I don't have citations for that or a strong argument for why unpacking specifically shouldn't be possible inside them. I'm open to suggestions.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • You're correct for a general case., but not here To ask a minimal question on them, named lambdas are better, than present an actual usage as it will complicate a thing. – Eir Nym May 03 '23 at 17:47
  • @EirNym Sorry, I'm not sure I understand. Are you saying, for the sake of OP's example, a named lambda is fine to take the place of an unnamed lambda? To fix up what you wrote, that'd be: *"You're correct for a general case, but not here. To ask a minimal question on lambdas, named lambdas are better than presenting an actual usage as it would complicate things."* – wjandrea May 03 '23 at 17:55
  • 1
    Yes, I'm saying, that to present a very specific problem named lambda is ok. Otherwise, `map` or other function should be used to provide an example. Functions has no such restrictions and it's easy to call `func(*args)`. Current case with lambdas is covered by another PEP3113, and your answer is about good practices. – Eir Nym May 03 '23 at 18:12