Python 3 map / lambda method with 2 inputs

I have a dictionary like the following in python 3:

ss = {'a':'2', 'b','3'} 

I want to convert all its values ​​to int using the map function, and I wrote something like this:

 list(map(lambda key,val: int(val), ss.items()))) 

but python complains:

TypeError :() missing 1 required positional argument: 'val'

My question is: how to write a lambda function with two inputs (e.g. key and val)

+8
python dictionary syntax lambda
source share
1 answer

ss.items() will give iterability, which gives tuples at each iteration. In your lambda function, you defined it to accept two parameters, but the tuple will be considered as one argument. Thus, the value is not 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 ignore the keys anyway, just use ss.values() , like this

     print(list(map(int, ss.values()))) # [3, 2] 
  • Otherwise, as suggested by Ashwini Chodhari using itertools.starmap ,

     from itertools import starmap print(list(starmap(lambda key, value: int(value), ss.items()))) # [3, 2] 
  • I would prefer a way to understand List

     print([int(value) for value in ss.values()]) # [3, 2] 

In Python 2.x, you could do it like this:

 print map(lambda (key, value): int(value), ss.items()) 

This function is called unpacking Tuple parameters. But this is removed in Python 3.x. Read more about this in PEP-3113

+16
source share

All Articles