pythondictionarylambdaiterable-unpacking

How to unpack a variable in a lambda function?


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)

Solution

  • 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}