18910140161

Python-如何使用Jinja迭代dict中的值列表?-堆栈溢出

顺晟科技

2022-10-19 13:51:16

45

我有一个带有值列表的dict,基本上每个键有10个值:

我正在使用它们在HTML中生成卡片,所以我需要每个卡片都有每个键的一个值。最后我会得到10张牌。下面是我的HTML和我用Jinja迭代dict的最新尝试:

Jinja sintax是怎么做的?


顺晟科技:

问题不在于语法,而在于您的数据--您以错误的方式组织数据。 然后所有的-循环都没有意义。

您有一个包含多个列表的词典,但您应该有一个包含多个词典的列表。

movies = {
'title': ['The Shawshank Redemption', 'The Godfather', ..., 'The Lord of the Rings: The Fellowship of the Ring'],
'year': ['1994', '1972', ..., '2001'],
'poster': ['url', 'url1', ..., 'url9'],
'rating': ['9.2', '9.1', ..., '8.8'],
'votes': ['2467733', '1705796', ..., '1732916']
}

,然后可以使用您的

movies = {
'title': ['The Shawshank Redemption', 'The Godfather', ..., 'The Lord of the Rings: The Fellowship of the Ring'],
'year': ['1994', '1972', ..., '2001'],
'poster': ['url', 'url1', ..., 'url9'],
'rating': ['9.2', '9.1', ..., '8.8'],
'votes': ['2467733', '1705796', ..., '1732916']
}

使用原始数据-循环方式错误。第一个循环的工作原理就像你得到了字符串,然后你试图将它与下一个循环一起使用--这就造成了你的问题。必须使用like with.

movies = {
'title': ['The Shawshank Redemption', 'The Godfather', ..., 'The Lord of the Rings: The Fellowship of the Ring'],
'year': ['1994', '1972', ..., '2001'],
'poster': ['url', 'url1', ..., 'url9'],
'rating': ['9.2', '9.1', ..., '8.8'],
'votes': ['2467733', '1705796', ..., '1732916']
}

编辑:

两个版本的完整工作代码。

  • TAG:
相关文章
我们已经准备好了,你呢?
2024我们与您携手共赢,为您的企业形象保驾护航