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..

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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 -.-
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"))

Comments

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.