我有以下未排序的词典(日期是键):
{“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}
我正在尝试从最旧到最新的排序。 我试过代码:
mydict = OrderedDict(sorted(mydict .items(), key=lambda t: t[0], reverse=True))
对它进行排序,几乎工作。它产生了排序的字典,但却忽略了几个月:
{“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}
我该如何解决这个问题?
编辑: 我需要这个来计算过去X天中每天在django应用程序中创建的对象。
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))
答案 0 :(得分:0)
您可以使用datetime
模块将字符串解析为实际日期:
>>> from datetime import datetime
>>> sorted(mydict .items(), key=lambda t:datetime.strptime(t[0], '%d-%m-%Y'), reverse=True)
答案 1 :(得分:0)
如果您想以{"22-09-2014": 0, 23-09-2014": 0, "localized date": count_for_that_date}
格式创建json响应,以便最早的日期出现在输出中,那么您可以event_chart
OrderedDict
:
event_chart = OrderedDict()
today = DT.date.today() # use DT.datetime.combine(date, DT.time()) if needed
for day in range(29, -1, -1): # last 30 days
date = today - DT.timedelta(days=day)
localized_date = formats.date_format(date, "SHORT_DATE_FORMAT")
day_count = Event.objects.filter(project=name, created=date).count()
event_chart[localized_date] = day_count
return HttpResponse(json.dumps(event_chart))