[{'birthday': '10/02/1987', 'id': '100003680523252', 'name': 'Station x Singapore'}, {'birthday': '05/21/1988', 'id': '100006891608724', 'name': 'Jessica x'}]
Asked
Active
Viewed 979 times
0
-
@SimonT It's not a duplicate of that as we're sorting a list here. The question should be closed anyway as there is no evidence of any working that has been done to solve this. – TerryA Apr 23 '14 at 01:30
-
@Haidro ah my bad, I was lost in all the code. Didn't notice the square brackets. – SimonT Apr 23 '14 at 01:32
-
If my answer was helpful, would you mind accepting it? Thank you – sshashank124 Apr 23 '14 at 03:31
2 Answers
3
You can do that as:
import datetime
a = [{'birthday': '10/02/1987', 'id': '100003680523252', 'name': 'Station x Singapore'}, {'birthday': '05/21/1988', 'id': '100006891608724', 'name': 'Jessica x'}]
a.sort(key=lambda x: datetime.datetime.strptime(x['birthday'], '%m/%d/%Y'))
>>> print a
[{'birthday': '10/02/1987', 'id': '100003680523252', 'name': 'Station x Singapore'}, {'birthday': '05/21/1988', 'id': '100006891608724', 'name': 'Jessica x'}]
Here the sort()
method sorts using lambda and the key as the birthday key of the list.
The datetime
module is important since it helps to properly order the dates since python will not compare the date strings as dates but rather as strings where 11/11/2002
will be greater than 02/02/2056
(due to char-by-char comparison) which is clearly not what you want. Treating the dates as a datetime
object will ensure that the datetime
modules date comparison feature is used instead.
Hope that helps

sshashank124
- 31,495
- 9
- 67
- 76
-
OP would likely benefit from just a bit of explanation on how `list.sort` works with `key = lambda...` and the `datetime` module. But good solution. – SimonT Apr 23 '14 at 01:34
-
-
1It looks like you haven't been "more careful", as you said you would [here](http://stackoverflow.com/questions/23041710/counting-the-number-of-words-in-a-string-in-python/23041720?noredirect=1#comment35204042_23041720) (You prob need 10k+ rep to see this). Don't answer questions that don't deserve to be answered, please. You shouldn't encourage this. – TerryA Apr 23 '14 at 01:42
0
Define a comparison function that turns the birthday into datetime objects, something like:
def cmp(x, y):
date_x = datetime.datetime.strptime(x, '%d/%m/%Y')
date_y = datetime.datetime.strptime(y, '%d/%m/%Y')
return date_x.cmp(date_y)

hd1
- 33,938
- 5
- 80
- 91