Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I sort this list in Python, if my date is in a String?

[{'date': '2010-04-01', 'people': 1047, 'hits': 4522}, {'date': '2010-04-03', 'people': 617, 'hits': 2582}, {'date': '2010-04-02', 'people': 736, 'hits': 3277}]

Suppose I have this list. How do I sort by "date", which is an item in the dictionary. But, "date" is a string...

like image 477
TIMEX Avatar asked Apr 07 '10 01:04

TIMEX


4 Answers

.sort(key=lambda x: datetime.datetime.strptime(x['date'], '%Y-%m-%d'))
like image 116
Ignacio Vazquez-Abrams Avatar answered Oct 26 '22 14:10

Ignacio Vazquez-Abrams


Fortunately, ISO format dates, which seems to be what you have here, sort perfectly well as strings! So you need nothing fancy:

import operator
yourlistofdicts.sort(key=operator.itemgetter('date'))
like image 31
Alex Martelli Avatar answered Oct 26 '22 14:10

Alex Martelli


Satoru.Logic's solution is clean and simple. But, per Alex's post, you don't need to manipulate the date string to get the sort order right...so lose the .split('-')

This code will suffice:

records.sort(key=lambda x:x['date'])
like image 17
damzam Avatar answered Oct 26 '22 14:10

damzam


In python 2.6 you can use soerted w/operator.itemgetter. Since date is YYYY-MM-DD it is sorted even though its a string cause its largest to smallest - i use that format all the time for this reason

>>> import operator
>>> l = [{'date': '2010-04-01','people': 1047, 'hits': 4522}, 
         {'date': '2010-04-03', 'people': 617, 'hits': 2582}, 
         {'date': '2010-04-02', 'people': 736, 'hits': 3277}]
>>> sorted( l, key = operator.itemgetter('date') )
[{'date': '2010-04-01', 'hits': 4522, 'people': 1047}, {'date': '2010-04-02', 'hits': 3277, 'people': 736}, {'date': '2010-04-03', 'hits': 2582, 'people': 617}]
like image 4
Rescommunes Avatar answered Oct 26 '22 14:10

Rescommunes