1

Python JSON array as show in example

[{
   "id":"3",
   "creator_id":"2131xxxxxxxx",
   "lowest_price_at":"2021-01-21T09:29:38-08:00",
   "status":"published",
   "status_changed_at":"2021-02-09T23:59:34-08:00",
   "origin_domain":"us"
},
{
   "id":"5",
   "creator_id":"2131xxxxxxxx",
   "lowest_price_at":"2021-01-15T09:29:38-08:00",
   "status":"published",
   "status_changed_at":"2021-02-09T23:59:34-08:00",
   "origin_domain":"us"
},
{
   "id":"1",
   "creator_id":"2131xxxxxxxx",
   "lowest_price_at":"2021-01-5T09:29:38-08:00",
   "status":"published",
   "status_changed_at":"2021-02-09T23:59:34-08:00",
   "origin_domain":"us"
}]

It's contained in live_items array. Now I need to sort that array by status_changed_at descending. Meaning first item in array needs to be the one with "id":"1"

from datetime import datetime
print(sorted(live_items, key=lambda x['status_changed_at']: datetime.strptime(x['status_changed_at'], "%Y-%m-%dT%H:%M:%S-08:00").strftime("%b %d %Y %I:%M%p")))

SyntaxError: expression cannot contain assignment, perhaps you meant "=="?

This I found on the thread sort dates in python array but I just stuck since i use first time lambda ex..

PyDeveloper
  • 309
  • 6
  • 24

2 Answers2

1

Just remove the array access in the lambda expression

key=lambda x['status_changed_at']: ...

and do

key=lambda x: ...

The array access is done later:

datetime.strptime(x['status_changed_at'] ...

For descending sorting, you also need

..., reverse=True)

Other than that, you need to rework your expression in strftime, because you have the month first and it's locale dependent. %Y%m%d%H%M probably sorts better.

Thomas Weller
  • 55,411
  • 20
  • 125
  • 222
  • 1
    that's driving me nuts for a very long time. Thank you. Sometimes i need to read documentation about i.e strftime before actually start using it -.- – PyDeveloper Feb 10 '21 at 09:03
1

You don't need to provide the key status_changed_at with lambda. The first parameter represent the element itself.

It should be:

from datetime import datetime
res = sorted(live_items,  key=
             lambda x: 
                 datetime.strptime(x['status_changed_at'], "%Y-%m-%dT%H:%M:%S-08:00").strftime("%b %d %Y %I:%M%p"))
Krishna Chaurasia
  • 8,924
  • 6
  • 22
  • 35