【问题标题】:Output sorted python dict within django template在 django 模板中输出排序的 python dict
【发布时间】:2012-12-01 05:42:40
【问题描述】:

我得到了一个 python dict,如下所示(由于隐私原因,重要信息被替换为“xxx”)。 我想在 django 模板中显示这个字典,但它应该是有序的,所以它应该以“A”开头,然后以“B”而不是“H”继续

这是我的字典(缩写):

{   'A': [   {'birthday_date': None,
             'first_name': 'Alberto',
             'last_name': 'xxx',
             'name': 'Alberto xxx',
             'uid': xxx},
         {   'birthday_date': None,
             'first_name': 'Antony',
             'last_name': 'xxx',
             'name': 'Antony xxx',
             'uid': xxx}],
'H': [   {   'birthday_date': '08/28',
             'first_name': 'Hitoshi',
             'last_name': 'xxx',
             'name': 'Hitoshi xxx',
             'uid': xxx}],
'C': [   {   'birthday_date': '05/07/1985',
             'first_name': 'Chr',
             'last_name': 'xxx',
             'name': 'Chr xxx',
             'uid': xxx}],
'E': [   {   'birthday_date': None,
             'first_name': 'Edimond',
             'last_name': 'xxx',
             'name': 'Edimond xxx',
             'uid': xxx},
         {   'birthday_date': '08/30',
             'first_name': 'Erika',
             'last_name': 'xxx',
             'name': 'Erika xxx',
             'uid': xxx}],
'B': [   {   'birthday_date': '08/16/1987',
             'first_name': 'Bhaktin',
             'last_name': 'xxx',
             'name': 'Bhaktin xxx',
             'uid': xxx}],
'I': [   {   'birthday_date': '08/25/1987',
             'first_name': 'Ivette',
             'last_name': 'xxx',
             'name': 'Ivette xxx',
             'uid': xxx}]}

这是我的 django 模板:

{% for letter, friend in bdays_all.items %}
    <h2>{{ letter }}</h2>
    {% for user in friend %}
         ...
    {% endfor %}
{% endfor %}

这很好用,但它没有排序。但这就是我需要的。我用 python 的 sorted() 函数尝试了一切,但没有任何成功。我只想订购字母。看起来微不足道,但我想不是。

有什么想法吗?

非常感谢!

【问题讨论】:

    标签: python django templates sorting dictionary


    【解决方案1】:

    字典未排序。

    您需要将您的 dict 转换为视图中的嵌套列表:最简单的方法就是调用 sorted(bdays_all.items())

    【讨论】:

    • 啊,我不知道。非常感谢您的回答,我会尽快接受。 (5 分钟)
    【解决方案2】:

    您还可以在视图中创建一个带有排序键的新字典:

    dictio = {'a': 'orange', 'c':'apple', 'b': 'bannana'}
    di = {}
    for key in sorted(dictio.iterkeys()):
        di[key] = dictio[key]
    

    结果:

    di = {'a': 'orange', 'b': 'bannana', 'c': 'apple'}
    

    【讨论】:

    • 字典是底层的哈希值,因此无法保证键的顺序。这就是 OrderedDict 存在的原因。
    猜你喜欢
    • 2016-01-16
    • 2019-10-18
    • 1970-01-01
    • 2012-10-15
    • 2019-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-08
    相关资源
    最近更新 更多