2011-01-21 152 views
59
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 

下面是輸出:Django的模板不能循環defaultdict

defaultdict(<type 'list'>, {'Smith': ['John', 'Samantha'], 'Spencer': ['shawn']}) 

和這裏的模板:

{% for lastname, firstname in data.items %} 
    <h1> {{ lastname }} </h1> 
    <p> {{ firstname|join:", " }} </p> 
{% endfor %} 

但在我的模板循環不起作用。什麼都沒有出現。它甚至不會給我一個錯誤。我怎樣才能解決這個問題?它應該以示與姓名沿姓氏,像這樣:

<h1> Smith </h1> 
<p> John, Samantha </p> 

<h1> Spencer </h1> 
<p> shawn </p> 
+0

您尚未顯示將字典放入模板上下文的代碼。你確定這是正確的發生? – 2011-01-21 22:02:16

+0

是的,其他所有東西都可以在循環之外正確渲染。 – user216171 2011-01-21 22:12:31

回答

36

嘗試:

dict(new_data) 

,並在Python 2,最好是使用iteritems代替items :)

+2

我不能相信像這樣簡單的事情。非常感謝! – user216171 2011-01-21 22:40:29

70

您可以通過在完成插入新值後禁用默認功能defaultdict來避免複製到新字典:

new_data.default_factory = None 

說明

template variable resolution algorithm in Django將嘗試解決new_data.itemsnew_data['items']首先,它使用defaultdict(名單)時解析爲一個空列表。

要禁用默認爲空列表,並有Django的上new_data['items']無法再繼續分辨率嘗試,直至調用new_data.items(),則default_factory attribute of defaultdict可以設置爲