about 1 year ago

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],  
       )
← Matplotlib display Chinese characters Pandas loc vs iloc →
 
comments powered by Disqus