import collections data = [ {'firstname': 'John', 'lastname': 'Smith'}, {'firstname': 'Samantha', 'lastname': 'Smith'}, {'firstname': 'shawn', 'lastname': 'Spencer'}, ] new_data = collections.defaultdict(list) for d in data: new_data[d['lastname']].append(d['firstname']) print new_data
Here's the conclusion:
defaultdict(<type 'list'>, {'Smith': ['John', 'Samantha'], 'Spencer': ['shawn']})
and here is the template:
{% for lastname, firstname in data.items %} <h1> {{ lastname }} </h1> <p> {{ firstname|join:", " }} </p> {% endfor %}
But the loop in my template does not work. I can not see anything. It doesn't even give me a mistake. How can i fix this? It should show the last name along with the first name, something like this:
<h1> Smith </h1> <p> John, Samantha </p> <h1> Spencer </h1> <p> shawn </p>
python loops django
user216171 Jan 21 2018-11-21T00: 00Z
source share