How to sort this list in Python?

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

How to sort the element "time", DESC.

+5
source share
1 answer

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 do not want to keep the original order, you can use your_list.sortthat changes the original list instead of creating a copy, for examplesorted(your_list)

l.sort(key=lambda a: a['time'], reverse=True)
+27
source

All Articles