PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, November 3, 2022

[FIXED] How to unpack a variable in a lambda function?

 November 03, 2022     dictionary, iterable-unpacking, lambda, python     No comments   

Issue

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}


Answered By - Andrej Kesely
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing