Home > Mobile >  Find a record from list of dictionary with multiple condition python
Find a record from list of dictionary with multiple condition python

Time:08-11

hi I have a scenario like

data = [
    {"name": "name1", "date": "1997-07-16 19:20:00 01:00" , 'last_modified':"1997-07-16 19:20:00 01:00"},
    {"name": "name3", "date": "2006-07-16 19:20:00 01:00" ,  'last_modified':"1997-07-16 19:20:00 01:00"},
    {"name": "name2", "date": "1992-07-16 19:20:00 01:00",  'last_modified':"1997-07-16 19:20:00 01:00"}]

and from this data I am getting latest record like this:

sorted_files = sorted(data, key=lambda d: d.get('last_modified', {}), reverse=True)

Now issue is in some cases last modified can be same . so In that case I have to compare their date field .and get the latest from date field . how I can do this using this 1 liner preferably ?

CodePudding user response:

IIUC, you can use a tuple as key:

sorted_files = sorted(data, key=lambda d: (d.get('last_modified', {}),
                                           d.get('date', {})
                                          ),
                      reverse=True)
sorted_files

output:

[{'name': 'name3',
  'date': '2006-07-16 19:20:00 01:00',
  'last_modified': '1997-07-16 19:20:00 01:00'},
 {'name': 'name1',
  'date': '1997-07-16 19:20:00 01:00',
  'last_modified': '1997-07-16 19:20:00 01:00'},
 {'name': 'name2',
  'date': '1992-07-16 19:20:00 01:00',
  'last_modified': '1997-07-16 19:20:00 01:00'}]
  • Related