Django 模板不能循环 defaultdict
问题描述:
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
输出如下:
defaultdict(<type 'list'>, {'Smith': ['John', 'Samantha'], 'Spencer': ['shawn']})
这是模板:
{% for lastname, firstname in data.items %}
<h1> {{ lastname }} </h1>
<p> {{ firstname|join:", " }} </p>
{% endfor %}
但是我模板中的循环不起作用.什么都不显示.它甚至没有给我一个错误.我怎样才能解决这个问题?它应该显示姓氏和名字,如下所示:
But the loop in my template doesn't work. Nothing shows up. It doesn't even give me an error. How can i fix this? It's supposed to show the lastname along with the firstname, something like this:
<h1> Smith </h1>
<p> John, Samantha </p>
<h1> Spencer </h1>
<p> shawn </p>
答
尝试:
dict(new_data)
并且在 Python 2 中最好使用 iteritems
而不是 items
:)
and in Python 2 it is better to use iteritems
instead of items
:)