python sort multiple keys code example

Example 1: python sort multiple keys

records.sort(
  key = lambda l: (l[0], l[2])
)

Example 2: python sorted dictionary multiple keys

mylist = sorted(mylist, key=itemgetter('name', 'age'))
mylist = sorted(mylist, key=lambda k: (k['name'].lower(), k['age']))
mylist = sorted(mylist, key=lambda k: (k['name'].lower(), -k['age']))

Example 3: python sort multiple keys

records.sort(
  key = lambda l: (l[0], l[2])
)

Example 4: python sort based on multiple keys

>>> def multisort(xs, specs):
...     for key, reverse in reversed(specs):
...         xs.sort(key=attrgetter(key), reverse=reverse)
...     return xs