I have the following data:
[
{
"id": 2,
"members": [
{
"id": 1,
"username": "stefan",
"email": "[email protected]"
},
{
"id": 9,
"username": "John",
"email": "[email protected]"
}
],
"title": "Conversation 2",
"messages": [
{
"message": "Conv 2 message 1",
"created_on": "03.05.2022 17:00",
"created_by": 1
},
{
"message": "Conv 2 message 2",
"created_on": "03.05.2022 17:00",
"created_by": 9
}
]
},
{
"id": 1,
"members": [
{
"id": 1,
"username": "stefan",
"email": "[email protected]"
},
{
"id": 11,
"username": "Sharon",
"email": "[email protected]"
}
],
"title": "Conversation 1",
"messages": [
{
"message": "Conv 1 message 1",
"created_on": "03.05.2022 17:12",
"created_by": 1
},
{
"message": "Conv 1 message 2",
"created_on": "03.05.2022 17:12",
"created_by": 11
},
]
},
]
Each dictionary represents a chat conversation and also contains a key for all the messages belonging to each chat convo.
My goal is for the list of convos to be sorted based on which one has the newest message (so based on the "created_on" key somehow)
Ie if the last chat message for chat 2 was May 9th at 5 pm and the last chat message for chat 1 was on May 9th at 3pm, I want the dictionary for chat 2 to be first in the list
I've been struggling to figure this out. I've tried:
new_list = data.sort(key=lambda x: ( x['messages']['created_on']))
But that doesn't work since the value of the messages key is another list and also I'd think sorting based on the date in this string format also wouldn't work.
Would appreciate any help
CodePudding user response:
You need to call max()
to get the latest chat message in each list.
new_list = sorted(data, key=lambda x: max(msg['created_on'] for msg in x['messages']))
But there's another problem. Your date strings are not in a format that can be ordered properly. You should change them to YYYY-MM-DD
format, or call datetime.strptime(msg['created_on'], '%d.%m.%Y %H:%M')
to parse them.