gpt4 book ai didi

python - Django模板不能循环defaultdict

转载 作者:IT老高 更新时间:2023-10-28 21:40:38 31 4
gpt4 key购买 nike

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 %}

但是我的模板中的循环不起作用。什么都没有出现。它甚至没有给我一个错误。我怎样才能解决这个问题?它应该显示姓氏和名字,如下所示:

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

<h1> Spencer </h1>
<p> shawn </p>

最佳答案

在插入新值后,您可以通过禁用 defaultdict 的默认功能来避免复制到新字典:

new_data.default_factory = None

说明

template variable resolution algorithm in Django将首先尝试将 new_data.items 解析为 new_data['items'],当使用 defaultdict(list) 时会解析为空列表。

要禁用默认为空列表并让 Django 在 new_data['items'] 上失败,然后继续解析尝试直到调用 new_data.items()default_factory attribute of defaultdict可以设置为

关于python - Django模板不能循环defaultdict,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4764110/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com