I have following unsorted dict (dates are keys):
{"23-09-2014": 0, "11-10-2014": 0, "30-09-2014": 0, "26-09-2014": 0, "03-10-2014": 0, "19-10-2014": 0, "15-10-2014": 0, "22-09-2014": 0, "17-10-2014": 0, "29-09-2014": 0, "13-10-2014": 0, "16-10-2014": 0, "12-10-2014": 0, "25-09-2014": 0, "14-10-2014": 0, "08-10-2014": 0, "02-10-2014": 0, "09-10-2014": 0, "18-10-2014": 0, "24-09-2014": 0, "28-09-2014": 0, "10-10-2014": 0, "21-10-2014": 0, "20-10-2014": 0, "06-10-2014": 0, "04-10-2014": 0, "27-09-2014": 0, "05-10-2014": 0, "01-10-2014": 0, "07-10-2014": 0}
I am trying to sort it from oldest to newest. I've tried code:
mydict = OrderedDict(sorted(mydict .items(), key=lambda t: t[0], reverse=True))
to sort it, and it almost worked. It produced sorted dict, but it has ignored months:
{"01-10-2014": 0, "02-10-2014": 0, "03-10-2014": 0, "04-10-2014": 0, "05-10-2014": 0, "06-10-2014": 0, "07-10-2014": 0, "08-10-2014": 0, "09-10-2014": 0, "10-10-2014": 0, "11-10-2014": 0, "12-10-2014": 0, "13-10-2014": 0, "14-10-2014": 0, "15-10-2014": 0, "16-10-2014": 0, "17-10-2014": 0, "18-10-2014": 0, "19-10-2014": 0, "20-10-2014": 0, "21-10-2014": 0, "22-09-2014": 0, "23-09-2014": 0, "24-09-2014": 0, "25-09-2014": 0, "26-09-2014": 0, "27-09-2014": 0, "28-09-2014": 0, "29-09-2014": 0, "30-09-2014": 0}
How can I fix this?
EDIT: I need this to count objects created in django application in past X days, for each day.
event_chart = {}
date_list = [datetime.datetime.today() - datetime.timedelta(days=x) for x in range(0, 30)]
for date in date_list:
event_chart[formats.date_format(date, "SHORT_DATE_FORMAT")] = Event.objects.filter(project=project_name, created=date).count()
event_chart = OrderedDict(sorted(event_chart.items(), key=lambda t: t[0]))
return HttpResponse(json.dumps(event_chart))
datetimeobjects to make them sort correctly - have a look at the docs. Alternatively, if you can change format to'yyyy-mm-dd'they will sort correctly as strings.