Home > Software design >  Sort a list of dictionary based on values of 'date', and the values are in the format dd-M
Sort a list of dictionary based on values of 'date', and the values are in the format dd-M

Time:03-22

I have data of the following type and my code for sorting is as followed by the example data:

list = [{ key1:'value',date:'14-APR-2021'}, {key1:'value', date:'15-MAR-2020'},{key1:'value', date:''}]
sorted_list = sorted(list, key = lambda i: i[date]]))

with this I am able to get

sorted_list = [{key1:'value', date:''},{ key1:'value',date:'14-APR-2021'}, {key1:'value', date:'15-MAR-2020'}]

i.e., it is being treated as a string

but the correct answer should be

sorted_list = [{key1:'value', date:''}, {key1:'value', date:'15-MAR-2020'}, { key1:'value',date:'14-APR-2021'}]

CodePudding user response:

Your date-format does not sort lexicographically, that's why you're getting the wrong result. One solution is to sort by the corresponding datetimes instead of the string representation.

from datetime import datetime

def to_date(s):
    try:
        return datetime.strptime(s, '%d-%b-%Y')
    except ValueError:
        return datetime.min
    
lst = [{'key1':'value', 'date':'14-APR-2021'}, {'key1': 'value', 'date': '15-MAR-2020'},{'key1': 'value', 'date':''}]
result = sorted(lst, key=lambda d: to_date(d['date']))
print(result)

Output:

[{'key1': 'value', 'date': ''}, {'key1': 'value', 'date': '15-MAR-2020'}, {'key1': 'value', 'date': '14-APR-2021'}]

CodePudding user response:

the date is in string format, so when you sort the list it is actually being compared based on the 'ascii' values of string characters

for example: 'a' is smaller/less than 'b' (ascii for 'a' is 97 and for 'b' is 98)

In this code,

14-APR-2021 with 15-MAR-2020

('4' < '5') in '14' and '15'

so, '4' is smaller than '5'.

  • Related