I have a dictionary like the following in python 3:
ss = {'a':'2', 'b','3'}
I want to convert all he values to int using map
function, and I wrote something like this:
list(map(lambda key,val: int(val), ss.items())))
but the python complains:
TypeError: () missing 1 required positional argument: 'val'
My question is how can I write a lambda
function with two inputs (E.g. key and val)
The map function has two arguments (1) a function, and (2) an iterable. Applies the function to each element of the iterable and returns a map object. The function can be (1) a normal function, (2) an anonymous function, or (3) a built-in function.
The map() function is a built-in function in Python, which applies a given function to each item of iterable (like list, tuple etc) and returns a list of results or map object. Note : You can pass as many iterable as you like to map() function.
In Python, a lambda function is a single-line function declared with no name, which can have any number of arguments, but it can only have one expression.
Create a Lambda function lambda : The key word of any lambda function. arguments : Input arguments of the function. The function allows multiple input arguments. expression : What the function will do in a single expression.
ss.items()
will give an iterable, which gives tuples on every iteration. In your lambda
function, you have defined it to accept two parameters, but the tuple will be treated as a single argument. So there is no value to be passed to the second parameter.
You can fix it like this
print(list(map(lambda args: int(args[1]), ss.items())))
# [3, 2]
If you are ignoring the keys anyway, simply use ss.values()
like this
print(list(map(int, ss.values())))
# [3, 2]
Otherwise, as suggested by Ashwini Chaudhary, using itertools.starmap
,
from itertools import starmap
print(list(starmap(lambda key, value: int(value), ss.items())))
# [3, 2]
I would prefer the List comprehension way
print([int(value) for value in ss.values()])
# [3, 2]
In Python 2.x, you could have done that like this
print map(lambda (key, value): int(value), ss.items())
This feature is called Tuple parameter unpacking. But this is removed in Python 3.x. Read more about it in PEP-3113
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With