python - 渲染计数器集合排序顺序

标签 python django collections

我不知道如何在 Django 中以正确的顺序显示 collections.Counter:当我使用 Counter().most_common(5) 时,它应该按顺序给我 5 个最常用的键。但事实并非如此。

我有这个:

users_cities = dict(Counter(User.objects.all().values_list('city', flat=True)).most_common(5)) 
return render(request,'admin/stats/stats.html', { 'users_cities': users_cities, }

但是当我在模板中循环遍历它们时,它们没有排序:

{% for label , counter in users_cities.items %}
  {% if label %}
  <tr>
    <th>{{ label }}</th><td> {{ counter }}</td>
  </tr>
  {% endif %}
{% endfor %}

那么我的错误在哪里呢?

最佳答案

您提取了最常见的内容,然后将它们放回新的字典中。字典是无序的。

跳过 dict 调用,只遍历从 most_common 获得的结果。

关于python - 渲染计数器集合排序顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39410954/

相关文章:

url - 为 Backbone Collection 使用动态 url

python - Pyparsing中的关键字匹配 : non-greedy slurping of tokens

python - 在树莓派上下载 dlib,尝试时 pip 一直输出错误?

django - 使用 Apache WSGI 通过 DJANGO_SETTINGS_MODULE 环境变量设置 Django 设置文件

c# - 'thread safe' 对象是什么意思?

c# - WPF Datagrid 分组和排序

python - 如何在 Facebook Marketing API 上查看事件的转换状态

python - 数字的 PLY 词法分析器始终返回 double

python - 如何在 django 模型中拥有字典字段并跨字典键对该字段使用聚合(最小/最大)

django - 编程错误 : when using order_by and distinct together in django