I have a django application, I use django-taggit for my blog.
Now I have a list of elements (actually objects) that I got from the database in one of my views below
tags = [<Tag: some>, <Tag: here>, <Tag: tags>, <Tag: some>, <Tag: created>, <Tag: here>, <Tag: tags>]
Now, how to find the count of each item in the list and return the list of tuples as shown below
the result should be lower
[(<Tag: some>,2),(<Tag: here>,2),(<Tag: created>,1),(<Tag: tags>,2)]
so that I can use them in the template, looping it to something like below
view
def display_list_of_tags(request): tags = [<Tag: some>, <Tag: here>, <Tag: tags>, <Tag: some>, <Tag: created>, <Tag: here>, <Tag: tags>] # After doing some operation on above list as indicated above tags_with_count = [(<Tag: some>,2),(<Tag: here>,2),(<Tag: created>,1),(<Tag: tags>,2)] return HttpResponse('some_template.html',dict(tags_with_count:tags_with_count))
template
{% for tag_obj in tags_with_count %} <a href="{% url 'tag_detail' tag_obj %}">{{tag_obj}}</a> <span>count:{{tags_with_count[tag_obj]}}</span> {% endfor %}
as described above, how to count the occurrences of each item in a list? The process should ultimately be fast, because I can have hundreds of tags in the tag app right?
If the list contains only strings as elements, we can use something like from collections import counter and calculate the counter, but how to do it in the above case?
My whole intention is to count cases and print them in a template like tag object and occurences ,
So, I'm looking for a fast and efficient way to perform the above functions?
Edit
So, I got the required answer from and I send the result to the template, converting the received list of tuples to a dictionary, as shown below
{<Tag: created>: 1, <Tag: some>: 2, <Tag: here>: 2, <Tag: tags>: 2}
and tried to print the aforementioned dictionary, looping it in a format like
{% for tag_obj in tags_with_count %} <a href="{% url 'tag_detail' tag_obj %}">{{tag_obj}}</a> <span>count:{{tags_with_count[tag_obj]}}</span> {% endfor %}
But its error display below
TemplateSyntaxError: Could not parse the remainder: '[tag_obj]' from 'tags_with_count[tag_obj]'
So how to display a dictionary in django templates using key and value?
Done, we can modify the template loop described above as shown below
{% for tag_obj, count in tags_with_count.iteritems %}