Django 模板字典显示顺序错误
我有一个字典,变量名叫做 division_total_display。
{87L: {'name': , 'total': 660L, 'total_percentage': 39, 'total_right': 256L}, 88L: {'name': , 'total': 660L, 'total_percentage': 42, 'total_right': 274L}, 89L: {'name': , 'total': 435L, 'total_percentage': 34, 'total_right': 148L}}
我把它传递到模板中,方法如下:
return render_to_response('site/report_topic_standard_stat.html',
{
'report_date' : report_date,
'et_display' : et_display,
'stats_display' : stats_display,
'division_total_display' : division_total_display,
'school' : school,
'board' : board,
'standard' : standard,
'standard' : standard,
'subject' : subject,
'from_time' : from_time,
'term_id' : term_id,
'white_label' : white_label,
},
context_instance=RequestContext(request)
但是在模板中,当我打印 {{division_total_display}} 时,
{88L: {'total_right': 274L, 'total': 660L, 'total_percentage': 42, 'name': }, 89L: {'total_right': 148L, 'total': 435L, 'total_percentage': 34, 'name': }, 87L: {'total_right': 256L, 'total': 660L, 'total_percentage': 39, 'name': }}
请注意顺序:它是从 88 开始的,而不是 87。
我希望它能从 87 开始,然后是 88 和 89。
2 个回答
1
可以试试用 OrderedDict。普通的Python字典是无序的——它们是通过哈希表实现的,这样会打乱键的顺序。
根据 字典的文档: “最好把字典想象成一个无序的键值对集合,要求每个键在一个字典中都是唯一的。”
4
字典是没有顺序的。如果你需要顺序,可以使用嵌套列表。