Django模板字典以错误的顺序显示

时间:2011-11-04 18:23:40

标签: python django templates

我有一个下面的字典。变量名称为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 个答案:

答案 0 :(得分:4)

字典无序。改为使用嵌套列表。

答案 1 :(得分:1)

请尝试使用OrderedDict。常规的python词典是无序的 - 它们是使用哈希表来实现的,哈希表会扰乱密钥顺序。

根据docs for dictionaries:“最好将字典视为一组无序的键:值对,并要求键是唯一的(在一个字典中)。”