aniztar
aniztar

Reputation: 2923

python : Sorting a list of dict basing on an element which is time string

I have a list of dicts. Among other elements, each dict in the list has a date and time element which looks like - 2018-08-14T14:42:14. I have written a function which compares two such strings and returns the most recent one. How do I use this to sort the list (most recent first)? Also, each dict is quite big in size hence, if possible, I would like to get the indices of array sorted (according to the time element) rather than the whole array. I have seen other similar questions on this site but all of them tell about sorting basing on a known data type like int or string.

Upvotes: 0

Views: 294

Answers (2)

leotrubach
leotrubach

Reputation: 1597

The dates written in ISO format have one nice property - if you sort them alphabetically, you sort them according to date values also (if the belong to one timezone, of course). Just use list.sort() function to do that. That will sort list in-place. Anyway you should not worry about memory, since creating the second sorted list will not take much memory since it holds references to dictionaries in the first list.

a = [
    {'time': '2018-01-02T00:00:00Z'},
    {'time': '2018-01-01T00:00:00Z'},
]

a.sort(key=lambda x: x['time'])
print(a)

Upvotes: 3

Deepak Saini
Deepak Saini

Reputation: 2910

We sort on the time by converting it to a python datetime object, which has natural ordering like int. So, you need not worry about the format of the time string.

# l is the list of the dicts, each dict contains a key "time". 
l = sorted(l, key=lambda x: datetime.datetime.strptime(x["time"], '%Y-%m-%dT%H:%M:%S'))

Upvotes: 2

Related Questions