【问题标题】:How to keep the ordering of key dictionary without sorting in loop?如何保持键字典的顺序而不循环排序?
【发布时间】:2017-12-21 08:27:24
【问题描述】:

我有一个字典键,如下所示:

 {% set ReportList = { 
   'T00004' : {'Title': 'Letter of Confirmation Loan'}, 
   'T00002' :{'Title': 'Repayment Schedule'},
   'T00010': {'Title': 'Letter of Hypothec'} } 
  %}

我想遍历这本字典,但我想保持字典的顺序没有排序,所以它应该像这样T00004, T00002, T00010。因此,我尝试了以下循环。

 {%for key in ReportList %} 
 {% set value = ReportList.get(key,{})%}
<tr class="link" onclick="CustomClickView('{{value.Title}}','Template/{{key}}')">
  <td width="10%">{{key}}</td>
  <td width="90%">{{value.Title}}</td>
</tr>
{%endfor%}

但是,结果为 T00002, T00004, T00010 有序,这与我上面的预期不同。

如何在不循环排序的情况下保持键字典的顺序?谢谢。

【问题讨论】:

标签: python sorting dictionary for-loop jinja2


【解决方案1】:

很简单,只需将OrderedDict 传入模板即可,例如:

# .py
render("index.html", OrderedDict=OrderedDict)

# .html
{% set ReportList = OrderedDict({ 
   'T00004' : {'Title': 'Letter of Confirmation Loan'}, 
   'T00002' :{'Title': 'Repayment Schedule'},
   'T00010': {'Title': 'Letter of Hypothec'} }) 
%}

然后你就可以像普通的OrderedDict一样使用它了。

【讨论】:

  • 这种方式真的很有效,非常感谢你:)
【解决方案2】:
import pprint

reportList = { 
   'T00004' : {'Title': 'Letter of Confirmation Loan'}, 
   'T00002' :{'Title': 'Repayment Schedule'},
   'T00010': {'Title': 'Letter of Hypothec'} } 


pprint.pprint(reportList.items())

#  dict_items([
#   ('T00004', {'Title': 'Letter of Confirmation Loan'})
#   ('T00002', {'Title': 'Repayment Schedule'}), 
#   ('T00010', {'Title': 'Letter of Hypothec'})])

for  num,d in reportList.items():
  print(num)

# T00004
# T00002
# T00010

【讨论】:

  • 抱歉,既然问题是jinja2 而不是python,我们如何在jinja2 上下文中做到这一点?谢谢。
  • 您能否添加一些评论细节而不仅仅是代码,因为要理解它的细节是什么以及它是如何工作的有点困难。谢谢。
猜你喜欢
  • 2020-11-30
  • 1970-01-01
  • 1970-01-01
  • 2019-06-24
  • 2017-04-26
  • 2020-11-01
  • 1970-01-01
  • 2017-10-10
  • 1970-01-01
相关资源
最近更新 更多