Schachjunge Schachjunge - 1 month ago 10x
Python Question

Render Counter Collections Sort Order

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.

I've got this:

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, }

But when i loop through them in the template, they arent sorted:

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

So where is my mistake?


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

Skip the dict call and just iterate through the result you get from most_common.