Sample data:
user_id = 1
project_id = 2
a = [{
"_id": {
"$oid": "63fda80f3ab1f908c146131d"
},
"data": {
"project_id": 2,
"user_id": 1,
"activity_message": "Success 1",
"activity_created_on": {
"$date": "2023-02-28T12:30:55.652Z"
}
}
},{
"_id": {
"$oid": "63fda80f3ab1f908c146131d"
},
"data": {
"project_id": 2,
"user_id": 1,
"activity_message": "Success 2",
"activity_created_on": {
"$date": "2023-02-28T12:36:55.652Z"
}
}
}]
I tried in this way: To sort the messages based on activity_created_on
key to get last entry first.
def tags(a):
tags = set()
for item in a:
if item.get('data'):
if all([item["data"]["user_id"]==user_id, item["data"]["project_id"]==project_id]):
q.r = item["data"]["activity_message"]item["data"]["activity_created_on"]["$date"]
tags.add(q,r)
return tags
print(tags(a))
I am trying to get the output as last come first serve based on activity_created_on
key.
Expected output:
Success 2
Success 1
3
Answers
Sets
do not necessarily preserve order, use alist
instead:Out:
If you want easy implementation, just use
list
insteadset
. Just create a list of objects which includesactivity_message
andactivity_created_on.$date
, so it can be reverse-sorted by that date. Try this:The output will be:
With this approach the function uses a
list comprehension
with.get()
method and returns a reversed list.print(*tags(a), sep="n")
unpacks the returned list and prints individual element in a new line.