python 3 map/lambda method with 2 inputs
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 thisprint(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
Related videos on Youtube
Mohammadreza
Updated on June 06, 2022Comments
-
Mohammadreza almost 2 years
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)-
jonrsharpe over 9 yearsYou've written it with two parameters just fine, but the problem is it is only being called with a single argument, a tuple
(key, val)
. -
BrenBarn over 9 yearsIf you don't want to do anything with the keys, why don't you just map on
ss.values()
? -
Ashwini Chaudhary over 9 yearsYou need to use
itertools.starmap
instead of plainmap
as it unpacks the arguments for us(but only if you're using both keys and values, otherwise it's unnecessary as BrenBarn pointed out). In Python 2 it was possible using simple tuple argument unpacking:lambda (key, val): int(val)
. -
jfs over 9 yearsHave you considered dict comprehension:
{k: int(v) for k, v in ss.items()}
Or if you want to modify the dict inplace:for k, v in ss.items(): ss[k] = int(v)
-
jfs over 9 yearsIf you need only values then:
values = map(int, ss.values())
-
Mohammadreza over 9 yearsThanks every one for their correct comments. especially Ashwini,For the difference between python 2 and 3.
-
-
Jon Clements over 9 yearsAny other ways you fancy mentioning? :p
-
jfs over 9 yearsOption zero is to call
ss.values()
:result = map(int, ss.values())
-
Mohammadreza over 9 yearsThank you for the holistic response. also thanks Ashwini for starmaps. I didnt know that difference in python 2 and 3. which was my main problem.