Skip to content Skip to sidebar Skip to footer

Sorting With Two Key= Arguments

I want a case-insensitive sort of a tuple of records (lists) on two fields in each record. HowTo/Sorting tells me how to do case-insensitive (key=str.lower), and it tells me how t

Solution 1:

The problem with your code is that you pass the same parameter twice. That is not possible.

They key argument of sorted expects a function. This function gets one element of the iterable and returns something that is sortable in the way you want.

Commonly, lambda functions (that means inline-functions) are used:

parts = [('A', 2, ''),
         ('a', 1, ''),
         ('b', 2, ''),
         ('B', 1, '')]
foo = sorted(parts, key=lambda s: (s[0].lower(), s[1]))
print(foo)

But you could also create a "real" function:

parts = [('A', 2, ''),
         ('a', 1, ''),
         ('b', 2, ''),
         ('B', 1, '')]

defmy_sorting(element):
    return (element[0].lower(), element[1])

bar = sorted(parts, key=my_sorting)
print(bar)

Both give

[('a', 1, ''), ('A', 2, ''), ('B', 1, ''), ('b', 2, '')]

You should also know that tuples are always sorted element by element. That means, first the list is sorted by the first element of all tuples. Then, for elements which have the same sorting key for the first element, the second element is used, etc.

Post a Comment for "Sorting With Two Key= Arguments"