Django pattern cannot loop by default

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> 
+57
python loops django
Jan 21 2018-11-21T00:
source share
2 answers

to try:

 dict(new_data) 

and in Python 2 it is better to use iteritems instead of items :)

+36
Jan 21 2018-11-21T00:
source share
โ€” -

You can avoid copying to a new dict by disabling the defaultdict default function after you finish inserting new values:

 new_data.default_factory = None 

Explanation

Django's variable template resolution algorithm will first try to resolve new_data.items as new_data['items'] , which resolves an empty list using defaultdict (list).

To disable default to an empty list and crash Django on new_data['items'] , continue resolving attempts until calling new_data.items() , the default_factory attribute defaultdict can set to None.

+69
Oct. 11 '12 at 15:05
source share



All Articles