There is a list of dictionaries below like
my_dictionary = [
{
'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' }
]
- I have two
namevalues asTesterorDeveloper - By checking latest
lastModifiedDateneed to extract latest entry forTester,Developer
Logic implemented in the below code is as follows:
- First sort the on the basis of
lastModifiedDatein descending order. - Extract the first occurrence in the list of dictionaries.
response = sorted(my_dictionary, 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
The output of the above code on input as the above list of the dictionaries is
[{'name': 'Tester',
'id': '101',
'status': 'Failed',
'lastModifiedDate': '2022-02-21 12:25:32:013302'}]
but the expected output 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 fail in case of the absence of Developer or Tester dictionary name values.
my_dictionary = [{'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'}]