1

I'm trying to sort a list of entries based on the id of the entries.

I tried this code, but it didn't work:

entries.sort(cmp=None, key=Entry.id, reverse=False)

The objects in the list are entries which have an id.

This is the error I get:

TypeError: 'InstrumentedAttribute' object is not callable

Any ideas?

0

2 Answers 2

7

key has to be a function that takes a list entry and returns a value used in comparison.

As alternative to lambda, use operator.attrgetter:

entries.sort(key=attrgetter('id'))
Sign up to request clarification or add additional context in comments.

1 Comment

this is much faster than the lambda solution
3

As the error told you, Key needs to be a function, or more accurately, a callable object.

entries.sort(cmp=None, key=(lambda x:x.id), reverse=False)

1 Comment

And you don't need the cmp= parameter. Not reverse either, of course, but it's OK to add the default for clarity. But in the case of cmp= no clarity is added.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.