Quantcast
Channel: Cheng's Blog
Viewing all articles
Browse latest Browse all 10

Python3's pass more than one parameter to lambda function

$
0
0

I was trying to do this in Python 3:

t = {'1': 1, '2':2}

#Trying to sort the dictionary t by its value
sorted(t.items(), 
       key=lambda (k,v): v,  # the left bracket raises syntax error, it works in python 2 but not 3
      )

It turns out that in Python 3, tuple parameter unpacking is not supported anymore.

So if more than one parameter is passed into a lambda function, we have to access it like a list:

lambda parameters: parameters[0], parameters[1], parameters[2]

So for the issues I have, the correct code would be:

sorted(t.items(), 
       key=lambda k_v: k_v[1],  
       )

Viewing all articles
Browse latest Browse all 10

Trending Articles