模板中出现KeyError,即使键确实存在
我想在模板中显示这样的数据:[{'name': '某个名字', 'description': '这个项目的描述'}]
我尝试使用这段代码:
{% for item in source_data %}
<tr>
<td>{{ item['name'] }}</td>
<td>{{ item['description'] }}</td>
</tr>
{% end %}
但是它不管用,因为我收到了KeyError: 'description'
的错误提示。
不过,如果我把第二个占位符改成{{ item.get('description') }}
,它就能正常工作了(从字典中正确打印了数据,而不是默认值)。
是什么导致了这种错误呢?
1 个回答
2
看起来你所有的字典里并不是每一个都有 description
这个键。
与其直接通过键来获取值,不如使用字典的 get() 方法,这样如果找不到某个键,就不会报 KeyError
错误:
{% for item in source_data %}
<tr>
<td>{{ item['name'] }}</td>
<td>{{ item.get('description', 'No description') }}</td>
</tr>
{% end %}
示例:
>>> from tornado import template
>>> source_data = [
... {'name': 'Some name', 'description': 'Description for this item'},
... {'name': 'test'}
... ]
>>> template1 = template.Template("""
... {% for item in source_data %}
... {{ item['description'] }}
... {% end %}
... """)
>>> template2 = template.Template("""
... {% for item in source_data %}
... {{ item.get('description', 'No description found') }}
... {% end %}
... """)
>>> print template1.generate(source_data=source_data)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "tornado/template.py", line 278, in generate
return execute()
File "<string>.generated.py", line 7, in _tt_execute
KeyError: 'description'
>>> print template2.generate(source_data=source_data)
Description for this item
No description found
希望这能帮到你。