Skip to main content
 首页 » 编程设计

python之在 Django 模板中使用字典字典效果不佳

2025年05月04日32daizhj

加权有向图在 Python 中表示为字典的字典。 像这样(示例):

digraph = {'a': {'b':2, 'c':3}, 'b': { 'a':1, 'd',2}} 

我的问题涉及将此二合字母对象传递给 Django 模板系统。 在此示例中,“a”、“b”、“c”、“d”是图的节点,有向图表示这些节点之间的连接以及由整数值给出的每个连接边的权重。

考虑一个通用节点:节点。

我在访问模板时遇到困难: digraph.node.items 。 对于任何字典 D,D.items 效果很好。但是当我们想要访问子字典的项目时(在上面的有向图中)。 这正是我想要的(但效果不佳):

{% for node in node_list %} 
  {% for adj_node,weight in digraph.node.items %} 
    {{ adj_node }}, {{ weight }} <br/> 
  {% endfor %} 
{% endfor %} 

adj_node 和 weight 不打印。

请您参考如下方法:

可以选择定义您自己的过滤器以从字典中提取感兴趣的值:http://ralphminderhoud.com/posts/variable-as-dictionary-key-in-django-templates/

简短版本:

在 project/app/templatetags/dictionary_extras.py 中:

from django import template 
register = template.Library() 
 
@register.filter(name='access') 
def access(value, arg): 
    return value[arg] 

在 urls.py 中:

url(r'^testing', 'views.vTestingLists', name='testing_lists'), 

在 views.html 中:

def vTestingLists(request): 
    context= {'d': {'a':'apple', 'b': 'banana', 'm':'mango', 'e':'egg', 'c':'carrot'}} 
    return render_to_response( 'testinglists.html', context ) 

在名为 testinglists.html 的模板中:

{% load dictionary_extras %} 
{% for key in d %} 
    {{ d|access:key }} 
{% endfor %} 

然后访问 …/testing URL 以查看您的手工结果。

这不是我的代码,所有归功于 Ralph Minderhoud(链接文章的作者)。我已经验证此代码可以从这个答案转录(而不是复制/粘贴)到我的 Django 1.1 环境中。