如何使用Python和Django以最大值到最低值列出字典中的所有项?

时间:2017-06-04 06:40:46

标签: python html django dictionary

所以我将此作为我的html文件。

<form method="post">
    {% csrf_token %}
    Problem: <input type="text" name="poi" autofocus>
    <input type="submit" value="Submit">
    <hr>
</form>
<br>
<ul>
    {% for u in sort %}
        <li>{{ u|safe }}</li>
    {% endfor %}
<ul>

我有一个名为sort的变量,它接受字典dictionary = {'hi': 5, 'hey': 3, 'hiya': 1}中的所有项目,并使用以下内容按最高值到最低值进行排序。

for w in sorted(dictionary, key=dictionary.get, reverse=True):
    sort.append(w)

现在列表按从高到低的顺序排列。正如您在html文件中看到的那样,我正在尝试按顺序打印它们。出了什么问题是它没有打印任何东西。我做错了什么?

编辑:请参阅以下render

try:
    return HttpResponse(request, 'patrec.html', {'sort':sort})
except:
    return render(request, 'patrec.html')

2 个答案:

答案 0 :(得分:2)

您以错误的方式使用HttpResponse。它注定要抛出异常,因为它不是它的工作方式。因此,它始终引发异常,并且在except块内,它将返回render的结果,而您没有将{'sort': sort}作为上下文传递。因此,只需删除tryexcept块以及HttpResponse。你应该只有这个:

return render(request, 'patrec.html', {'sort': sort})

答案 1 :(得分:0)

你可以用

做到这一点
import heapq
list1=heapq.nlargest(len(dict1), dict1, key=dict1.get)
print(list1)

其中,dict1是字典名称。

由于heapq内置于Python 3中,因此您无需进行任何安装。