15
[{'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...

TIMEX
  • 259,804
  • 351
  • 777
  • 1,080

5 Answers5

45
.sort(key=lambda x: datetime.datetime.strptime(x['date'], '%Y-%m-%d'))
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
27

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'))
Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
18

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'])
damzam
  • 1,921
  • 15
  • 18
  • 1
    ...And once again the simplest, most Pythonic, and correct answer is hastily brushed aside when the asker is too hasty *sighs*. – Humphrey Bogart Apr 07 '10 at 02:41
  • 1
    Upvoted for simplicity, but definitely requires dates to be in YYYY-MM-DD format (which therefore sort similarly as strings). – dkamins Apr 07 '10 at 07:23
4

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}]
Rescommunes
  • 805
  • 1
  • 8
  • 15
2
records = [
     {'date': '2010-04-01', 'people': 1047, 'hits': 4522}, 
     {'date': '2010-04-03', 'people': 617, 'hits': 2582}, 
     {'date': '2010-04-02', 'people': 736, 'hits': 3277}
     ]
records.sort(key=lambda x: x['date'].split('-'))
satoru
  • 31,822
  • 31
  • 91
  • 141
  • Note that this sort won't work if the dates aren't zero-filled. For, example 2-1 would come after 10-1, even though February comes before October. – Rose Perrone Jul 27 '12 at 23:06