-3

I have a list like:

a = [
{
"dt_1":datetime.datetime(...),
"duration_milliseconds":<int>
},
{
"dt_1":datetime.datetime(...),
"duration_milliseconds":<int>
},
{
"dt_1":datetime.datetime(...),
"duration_milliseconds":<int>
},
{
"dt_1":datetime.datetime(...),
"duration_milliseconds":<int>
}
]

I want to sort this list this way: First sort by dt_1 (older datetimes first), then if some dt_1's are the same sort by duration_milliseconds (little durations first).

Thanks in advance,

Chris Pappas

Chris P
  • 2,059
  • 4
  • 34
  • 68
  • Does this answer your question? [Custom Python list sorting](https://stackoverflow.com/questions/11850425/custom-python-list-sorting) – Timus Jun 14 '23 at 10:41

2 Answers2

0

Sure.

The key= argument for list.sort() and sorted() defines a function to use as a sort key for a given item in the iterable, and returning a tuple from that function does what you want, since tuples are compared item-wise:

a.sort(key=lambda p: (p["dt_1"], p["duration_milliseconds"]))
AKX
  • 152,115
  • 15
  • 115
  • 172
  • One extra question: Is it possible to except one list item from order (let it be the last item)? I know i can permantly delete it but is there any easier way? – Chris P Jun 14 '23 at 07:31
  • It'll probably be easiest to `pop` the last item out, sort the rest, then `append` it back in. – AKX Jun 14 '23 at 08:13
0

Since you have different ordering for every value you need to order in reverse by the negative of the ints

a.sort(key=lambda x: (x['dt_1'], -x['duration_milliseconds']), reverse=True)
Guy
  • 46,488
  • 10
  • 44
  • 88