所以我将此作为我的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')
答案 0 :(得分:2)
您以错误的方式使用HttpResponse
。它注定要抛出异常,因为它不是它的工作方式。因此,它始终引发异常,并且在except
块内,它将返回render
的结果,而您没有将{'sort': sort}
作为上下文传递。因此,只需删除try
和except
块以及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中,因此您无需进行任何安装。