Haus
Haus

Reputation: 1492

Python sorted() with itemgetter and comparer

I have a comparer function that is being wrapped with functools.cmp_to_key so that I can use it when calling sorted().

The problem is that I am already using itemgetter as the key. The itemgetter is being used to retrieve a value from a dictionary, and this value is what is being used to sort the collection.

So, essentially, I need to be using the itemgetter to retrieve the values, and then I need to use the comparer function to properly sort them.

I have tried the following combinations, but none seem to work:

for x in range( 0, len(sort_columns) ):
  comparer = cmp_to_key(sort_columns[x].sort_func)
  results = sorted( data, key=comparer )
  results = sorted( data, key=comparer(itemgetter( sort_columns[x] ) ) )
  results = sorted( data, key=itemgetter( comparer( sort_columns[x] ) ) )

In cases where a specific comparer isn't needed, it is just called as:

results = sorted( data, key=itemgetter( sort_columns[x] ) )

Upvotes: 2

Views: 206

Answers (1)

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 95948

You need to compose the getter and the comparer. Something to the effect of:

for columns in sort_columns: # don't use a range loop unless you need to
    comparer = cmp_to_key(columns.sort_func)
    getter = itemgetter(columns)
    data = sorted(data, key=lambda x: comparer(getter(x)))

Upvotes: 2

Related Questions