how can i fetch the activity_message value if given conditions are verified using python
Question:
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
python
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 = item["data"]["activity_message"]
tags.add(q)
return tags
print(tags(a))
Iam trying to get the output as ‘last come first serve’ based on "activity_created_on key".
expected output:
Success 2
Success 1
Answers:
If it is enough to just reverse your set before returning it, you can try this.
return sorted(tags, reverse=True)
Otherwise you could put the found date also into a tuple and then later on sort by that date and then return split up your tuple to get rid of the date.
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
python
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 = item["data"]["activity_message"]
tags.add(q)
return tags
print(tags(a))
Iam trying to get the output as ‘last come first serve’ based on "activity_created_on key".
expected output:
Success 2
Success 1
If it is enough to just reverse your set before returning it, you can try this.
return sorted(tags, reverse=True)
Otherwise you could put the found date also into a tuple and then later on sort by that date and then return split up your tuple to get rid of the date.