skip to Main Content

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


  1. Sets do not necessarily preserve order, use a list instead:

    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"
            }
        }
    }]
    
    
    def tags(a):
        tags = []  # Set default item!
        for item in a:
            data = item.get('data')
            if data and data["user_id"] == user_id and data[
                    "project_id"] == project_id:
                tags.append(data["activity_message"])
        return tags[::-1] # reverse!
    
    
    print(tags(a))
    

    Out:

    ['Success 2', 'Success 1']
    
    Login or Signup to reply.
  2. If you want easy implementation, just use list instead set. Just create a list of objects which includes activity_message and activity_created_on.$date, so it can be reverse-sorted by that date. Try this:

    def tags(a):
        tags = []
        for item in a:
           if item.get('data'):
               if all([item["data"]["user_id"]==user_id, item["data"]["project_id"]==project_id]):
                q  =  {"am": item["data"]["activity_message"],"d": item["data"]["activity_created_on"]["$date"] }
                tags.append(q)
        return tags
    # print(tags(a))
    result = sorted(tags(a), key=lambda x: x['d'], reverse=True)
    for i in result:
      print(i["am"])
    

    The output will be:

    Success 2
    Success 1
    
    Login or Signup to reply.
  3. With this approach the function uses a list comprehension with .get() method and returns a reversed list.

    def tags(a):
        return [log["data"]["activity_message"] for log in a
                    if log["data"].get("user_id") == user_id and
                    log["data"].get("project_id") == project_id][::-1]
        
    print(*tags(a), sep="n")
    

    Success 2
    Success 1
    

    print(*tags(a), sep="n") unpacks the returned list and prints individual element in a new line.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search