5

[ {'time':33}, {'time':11}, {'time':66} ]

How to sort by the "time" element, DESC.

1 Answer 1

27

Like this:

from operator import itemgetter
l = sorted(l, key=itemgetter('time'), reverse=True)

Or:

l = sorted(l, key=lambda a: a['time'], reverse=True)

output:

[{'time': 66}, {'time': 33}, {'time': 11}]

If you don't want to keep the original order you can use your_list.sort which modifies the original list instead of creating a copy like sorted(your_list)

l.sort(key=lambda a: a['time'], reverse=True)
Sign up to request clarification or add additional context in comments.

2 Comments

the operator.itemgetter version is preferred. It has one less function call for each element.
@nosklo, itemgetter actually returns a function that works almost the same as lambda a: a['time'] so there isn't really much of a difference from this prospective. Both methods involves a function call for each element.

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.