在模板django中打印(未分类)dictonary

时间:2016-02-15 18:00:45

标签: html django templates dictionary django-templates

我有一个dict列表:

Dict = [ {'key1':'value1', 'key2':'value2','key3':'value3'},
        {'key1':'value4', 'key2':'value5','key3':'value6'},
        {'key1':'value7', 'key2':'value8','key3':'value9'}]

我需要按此顺序显示它:

KEY1     KEY2   KEY3
value1  value2  value3
value4  value5  value6
value7  value8  value9

按照此顺序,按键必须只打印一次。

现在我在模板中有这个代码,但是这些值与键的列不匹配:

<table border="1">
    <tr>
        {% for k in listkey %}
            <td>{{ k }}</td>
        {% endfor %}
    </tr>
        {% for raw in dict %}
        <tr>
            {% for k,v in raw.items %}
                <td>{{ v }}</td>
            {% endfor %}
        </tr>
        {% endfor %}
</table>

在views.py中:

listkeys = ['key1','key2','key3']

请帮我解决这个问题。谢谢!

2 个答案:

答案 0 :(得分:1)

Dict列表中,您可以创建包含key值的词典作为键,value将是前一列表中所有组合值的list

# use lowercase variable names and dont pick name like "list", "dict", "tuple" etc.

from collections import defaultdict

your_list = [{'key1':'value1', 'key2':'value2','key3':'value3'},
             {'key1':'value4', 'key2':'value5','key3':'value6'},
             {'key1':'value7', 'key2':'value8','key3':'value9'}]

output = defaultdict(list)
for d in your_list:
    for key, value in d.items():
        output[key].append(value)

输出将是

defaultdict(list,
            {'key1': ['value1', 'value4', 'value7'],
             'key2': ['value2', 'value5', 'value8'],
             'key3': ['value3', 'value6', 'value9']})

关于小写变量名称PEP-8

答案 1 :(得分:0)

由于你已经注意到,python中的dict是未排序的,所以除非你在模板中明确指定要访问哪个值,否则无法以任何顺序循环dict。

您可以改为更改数据结构,以构建列表列表:

another_datastructure = []

for item in Dict:
    # temp would hold value of key1, key2, key3 on current dict entry
    temp = []
    for key in listkeys:
        temp.append(Dict[key])
    another_datastructure.append(temp)

现在您有一个列表列表,每个列表都有key1,key2 key3 order之后的键。然后你可以循环它并保证订单。