相关疑难解决方法(0)

为什么在迭代python中的字典时必须调用.iteritems()?

为什么必须调用iteritems()迭代字典中的键值对?即

dic = {'one':'1', 'two':'2'}
for k, v in dic.iteritems():
    print k, v
Run Code Online (Sandbox Code Playgroud)

为什么不是迭代字典的默认行为

for k, v in dic:
    print k, v
Run Code Online (Sandbox Code Playgroud)

python dictionary loops

130
推荐指数
2
解决办法
8万
查看次数

在Django模板中使用变量作为字典键

我想在Django模板中使用变量作为字典中的键.我不能为我的生活弄明白该怎么做.如果我有一个带有名称或ID字段的产品,以及带有产品ID索引的评级字典,我希望能够说:

{% for product in product_list %}
     <h1>{{ ratings.product.id }}</h1>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

在python中,这将通过简单的方式完成

ratings[product.id]
Run Code Online (Sandbox Code Playgroud)

但我不能让它在模板中工作.我试过用...没有骰子.想法?

django django-templates

55
推荐指数
4
解决办法
4万
查看次数

Django模板中带空格的dict键

我试图在我的view.py中提供HTML模板中的字典,例如:

test = { 'works': True, 'this fails':False }
Run Code Online (Sandbox Code Playgroud)

并在模板中:

这没有问题:

{{ test.works }}
Run Code Online (Sandbox Code Playgroud)

但是,在"此失败"之类的单词之间有空格的字典键不起作用:

{{ test.this fails }}
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

无法解析余数:' fails'来自'this fails'

我怎样才能克服这个问题?我不是填充模型的人,因此我无法更改dict的键以删除空格.

python django whitespace django-templates

12
推荐指数
1
解决办法
4456
查看次数

django模板和列表字典

我正在使用django的模板系统,我遇到了以下问题:

我将字典对象example_dictionary传递给模板:

example_dictionary = {key1 : [value11,value12]}
Run Code Online (Sandbox Code Playgroud)

我想做以下事情:

{% for key in example_dictionary %}
// stuff here (1)
{% for value in example_dictionary.key %}
// more stuff here (2)
{% endfor %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

但是,这不会进入第二个for循环.

的确,如果我放

{{ key }}
Run Code Online (Sandbox Code Playgroud)

在(1)上,它显示正确的键,但是,

{{ example_dictionary.key }}
Run Code Online (Sandbox Code Playgroud)

没有显示.

这个答案中,有人建议使用

{% for key, value in example_dictionary.items %}
Run Code Online (Sandbox Code Playgroud)

但是,这在这种情况下不起作用,因为我希望(1)具有关于特定键的信息.

我该如何实现这一目标?我错过了什么吗?

django django-templates

9
推荐指数
1
解决办法
5670
查看次数