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
[{'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'}]
Also code should not fails absence of Developer or Tester
dictionary
myd = [ { 'name': 'Tester', 'id': '101', 'status': 'Failed', 'lastModifiedDate': '2022-02-14 12:25:32:013302' }, { 'name': 'Tester', 'id': '101', 'status': 'Failed', 'lastModifiedDate': '2022-02-21 12:25:32:013302' } ]
CodePudding user response:
If pandas
is in play:
import pandas as pd
df = pd.DataFrame(myd)
maxes = df.groupby('name')['lastModifiedDate'].transform('max')
result = df[df['lastModifiedDate'] == maxes].to_dict(orient='records')
Output:
>>> result
[{'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'}]
CodePudding user response:
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)
developer_lastest = sorted(developer, key=lambda x: x["lastModifiedDate"], reverse=True)
response_latest = [
tester_latest[0] if len(tester_latest) > 0 else None,
developer_lastest[0] if len(developer_lastest) > 0 else None
]
response_latest = list(filter(None, response_latest)
response_latest