Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to extract from the list of dictionary by checking latest timestamp and value

I have list of dictionary below

  • I have two name values [‘Tester’, ‘Developer’]
  • By checking lastModifiedDate need to extract latest entry for ‘Tester’, ‘Developer’
myd = [
  {
    'name': 'Tester',
    'id': '101',
    'status': 'Failed',
    'lastModifiedDate': '2022-02-14 12:25:32:013302'  },
  {
    'name': 'Developer',
    'id': '102',
    'status': 'Success',
    'lastModifiedDate': '2022-02-14 12:25:32:013302',
  },
  {
    'name': 'Tester',
    'id': '101',
    'status': 'Failed',
    'lastModifiedDate': '2022-02-21 12:25:32:013302'  }
]

My logic and code is below

  • First sort the lastModifiedDate
  • Extract the first occurence
response = sorted(myd,
                          key=lambda x: x['lastModifiedDate'],
                          reverse=True)

response_latest = []
for item in response:
    extracted_response = {}
    for field in item:     
        if item['name'] == 'Tester':
            extracted_response[field] = item[field]
    response_latest.append(extracted_response)
    break
    for field in item:     
        if item['name'] == 'Developer':
            extracted_response[field] = item[field]
    response_latest.append(extracted_response)
    break
response_latest

My out is

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[{'name': 'Tester',
  'id': '101',
  'status': 'Failed',
  'lastModifiedDate': '2022-02-21 12:25:32:013302'}]

Expected out is

[{'name': 'Tester',
  'id': '101',
  'status': 'Failed',
  'lastModifiedDate': '2022-02-21 12:25:32:013302'},
 {'name': 'Developer',
  'id': '102',
  'status': 'Success',
  'lastModifiedDate': '2022-02-14 12:25:32:013302'}]

>Solution :

I tried filtering myd and then finding the latest of each one.

tester = list(filter(lambda x: x["name"] == "Tester", myd))
developer = list(filter(lambda x: x["name"] == "Developer", myd))

tester_latest = sorted(tester, key=lambda x: x["lastModifiedDate"], reverse=True)[0]
developer_lastest = sorted(developer, key=lambda x: x["lastModifiedDate"], reverse=True)[0]

response_latest = [tester_latest, developer_lastest]
response_latest
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading