Вопрос

I have a dictionary of this format:

   ['This a text','Sat Nov 26 2011', .....],['This is another text','Sat Aug 26 2012',...],.....

I would like to sort this dictionary based on the second field i.e, timestamp in the format: Sat Nov 26 2011. I realize a similar question has been asked (Sort dictionaries based on timestamp in python) but the timestamp in that question is an integer. Could anyone please let me know how to do this?

Thanks!

Это было полезно?

Решение

(that is a list of lists, not a dict)

You just need to provide the mapping to turn each element of your list into a datetime object, which will sort appropriately.

from datetime import datetime
sorted(li, key=lambda x: datetime.strptime(x[1], '%a %b %d %Y'))

Другие советы

Having your list of items to sort:

lst = [['This a text','Sat Nov 26 2011', .....],['This is another text','Sat Aug 26 2012',...], ...]

and functions, which can convert datetime string into datetime data structure (which is already sortable):

def datestr2datetime(datestr):
    return datetime.datetime.strptime(datestr, "%a %b %d %Y")

You can create sorted list:

sortedlst = sorted(lst, key = lambda itm: datestr2datetime(itm[1]))

The lambda function creates a function, which is able converting particular items in your list into some values, which are then sorted and are determining final order of original items in the lst.

You need to use the sorted(key=) syntax from the answer you linked to along with converting the date strings to actual date objects.

>>> from datetime import datetime
>>> a = [['more text','Sat Jan 10 2013'],['other text','Sat Aug 14 2014'],['text','Sat Jul 27 2005']]
>>> sorted(a, key=lambda x: datetime.strptime(x[1],'%a %b %d %Y'))
[['text', 'Sat Jul 27 2005'], ['more text', 'Sat Jan 10 2013'], ['other text', 'Sat Aug 14 2014']]

The formatting rules for strptime will depend on how exactly the string is formatted.

Alternatively, if you want to modify the list in-place, the list.sort() method takes the same key param.

>>> a.sort(key=lambda x: datetime.strptime(x[1],'%a %b %d %Y'))
>>> a
[['text', 'Sat Jul 27 2005'], ['more text', 'Sat Jan 10 2013'], ['other text', 'Sat Aug 14 2014']]
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top