Render Counter Collections Sort Order
<p>I can't figure out how to display a collections.Counter in the right order in Django: When i use Counter().most_common(5) it should give me the 5 most common keys in order. But it does not.</p>

<p>I've got this:</p>

<pre><code>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, }
</code></pre>

<p>But when i loop through them in the template, they arent sorted:</p>

<pre><code>{% for label , counter in users_cities.items %}
  {% if label %}
  &lt;tr&gt;
    &lt;th&gt;{{ label }}&lt;/th&gt;&lt;td&gt; {{ counter }}&lt;/td&gt;
  &lt;/tr&gt;
  {% endif %}
{% endfor %}
</code></pre>

<p>So where is my mistake?</p>

<p>You extracted the most common, but then put them back into a new dict. Dicts are unordered.</p>

<p>Skip the <code>dict</code> call and just iterate through the result you get from <code>most_common</code>.</p>

python django collections