【发布时间】:2017-12-15 11:33:09
【问题描述】:
我目前正在尝试将两个 Python 字典排序到一个 HTML 数组中,例如:
#Headers
DictA = {'value': 'valeur', 'name': 'nom' }
#Data
DictB = {'value': '456', 'name': 'Test' }
我想对这两个字典进行排序,以使DictB 中的'456' 等于DictA 中的键'value'。
注意:我使用了除DictA 和DictB 之外的其他字典,这只是一个示例。但它适合我的问题。
在我的views.py 中,我定义了我的两个字典,例如:
headers = json.loads(entries[0].form_data_headers)
data = json.loads(entries[1].saved_data)
valuesData = data.values()
然后我通过上下文将它们传递给template.html:
context = {'entries': entries, 'form_entry_id': form_entry_id, 'headers': headers, 'data': data, 'valuesData': valuesData}
因此,在我的模板中,它将打印一个包含标题 (DictA) 和数据 (DictB) 的数组。
在我的模板中,我编写了以下代码:
<thead>
<!-- Test pr voir si les values sont pris en compte ou non -->
<p>{{valuesData}}</p>
<tr>
{% for entry in headers %}
<td>
{{ entry }}
</td>
{% endfor %}
</tr>
</thead>
数据在另一个for循环中:
<tbody>
<thead>
<!-- Test pr voir si les values sont pris en compte ou non -->
<p>{{valuesData}}</p>
<tr>
{% for entry in dataValues %}
<td>
{{ entry }}
</td>
{% endfor %}
</tr>
</thead>
</tbody>
结果如下:
- name 等于 456(而不是表单的名称)
- geom 等于测试(而不是我的坐标)
等等
它与正确的标题不匹配。
我正在考虑制作两个 for 循环,其中包含 if 语句:
{%if headers['name'] == dataValues['name']%}
<td>dataValues['name']</td>
但我收到一个错误,因为无法解析 dataValues['name']。
其余的代码是Javascript:
{% endblock content %}
{% block javascript %}
<script type="text/javascript">
function GetURLParameter(param_name){
var sPageURL = window.location.search.substring(1);
var sParameterName = sPageURL.split('=');
return sParameterName[1];
}
var name= GetURLParameter(name);
document.querySelector('.page-header .value').innerHTML = name;
</script>
{% endblock %}
{% block main-content-inner-attrs %}
{% endblock main-content-inner-attrs %}
{% block sidebar-wrapper %}
{% endblock sidebar-wrapper %}
其余代码在 javascript 中:
{% endblock content %}
{% block javascript %}
<script type="text/javascript">
function GetURLParameter(param_name){
var sPageURL = window.location.search.substring(1);
var sParameterName = sPageURL.split('=');
return sParameterName[1];
}
var name= GetURLParameter(name);
document.querySelector('.page-header .value').innerHTML = name;
</script>
{% endblock %}
{% block main-content-inner-attrs %}
{% endblock main-content-inner-attrs %}
{% block sidebar-wrapper %}
{% endblock sidebar-wrapper %}
【问题讨论】:
-
你有没有想过使用
dict.update?即dataValues.update(headers).
标签: python django sorting dictionary