目的是从字典中提取数据并以表格的形式返回键值对 这是我的Python代码的一部分:
dictionary = dict()
dictionary = {'hello': 1, 'hi': 2, 'go': 3}
output = template('make_table', wordList=dictionary)
return output
这是我的make_table.tpl文件的一部分:
<table>
%for index in wordList:
<tr>
<td>{{index}} </td>
</tr>
%end
</table>
不幸的是,tpl文件只会显示键:'hello','hi'和'go',但不是它们的值。
我想要的是能够显示:
你好1 hi 2 go 3
有人能告诉我如何在tpl文件中索引值吗?
答案 0 :(得分:4)
您可以使用iteritems()
:
<table>
%for key, value in wordList.iteritems():
<tr>
<td>{{key}} </td>
<td>{{value}} </td>
</tr>
%end
</table>
演示:
>>> from bottle import template
>>> t = """
... <table>
... %for key, value in wordList.iteritems():
... <tr>
... <td>{{key}} </td>
... <td>{{value}} </td>
... </tr>
... %end
... </table>
... """
>>> print template(t, wordList={'hello': 1, 'hi': 2, 'go': 3})
<table>
<tr>
<td>go </td>
<td>3 </td>
</tr>
<tr>
<td>hi </td>
<td>2 </td>
</tr>
<tr>
<td>hello </td>
<td>1 </td>
</tr>
</table>