0

I am upgrading to python 3.5.2 from python 2.6, And i have changed to python 3.5.2 and fixed almost all of the changes. now i am facing an issue while sorting a list.

My previous code is as follows :

somelist_variable = [{"idx" : 9, "name": "Syed"}, {"idx": 2, "name": "Mex"}]
somelist_variable.sort(lambda a, b: int(a.get("idx")) - int(b.get("idx")))

this above code works fine in python 2.6 , however it is giving an error python 3.5.2, i have checked alot of places to pass 2 parameters to the lambda but i couldnt find anything. Can anyone of you guys help me out with it.

Thanks.

Talenel
  • 422
  • 2
  • 6
  • 25
Syed Abdul Qadeer
  • 455
  • 1
  • 6
  • 14

3 Answers3

1

Okay, can U explain what u want? If U just want to sort somelist_variable by "idx" keyword argument u should write:

somelist_variable.sort(key=lambda a: int(a.get("idx")))

or advanced

from operator import itemgetter
somelist_variable.sort(key=itemgetter('idx'))
0

This should works in your case

somelist_variable = sorted(somelist_variable, key = lambda x: x.get("idx"))
Oleksandr Dashkov
  • 2,249
  • 1
  • 15
  • 29
0

The function should only take one argument. The smaller the return value, the earlier in the list the element will be placed:

somelist_variable.sort(key=lambda a: int(a.get("idx")))

Also, you have to explicitly specify that the argument to list.sort is a key.

jmd_dk
  • 12,125
  • 9
  • 63
  • 94