简体   繁体   English

如何在django上下文的字典中迭代元组值

[英]How do you iterate tuple values in a dictionary for django context

I am trying to push a Django context dictionary to a template. 我正在尝试将Django上下文字典推送到模板。

I have a bunch of values for songs and created a dictionary with tuple values like so: 我有一堆歌曲的值,并创建了一个包含元组值的字典,如下所示:

songs = {'titles': ('Hello', 'Umbrella'), 'artists': ('Adele', 'Rihanna')}

How do I loop it to output: 我如何循环输出:

Hello
Adele

Umbrella
Rihanna

Or maybe I should rethink my context dictionary setup? 还是我应该重新考虑上下文词典的设置?

Do this: 做这个:

for title, artist in zip(songs['titles'], songs['artists']):
    print(title)
    print(artist)
    print() # In Python 2, remove the parentheses

In your view: 您认为:

titles = ('Hello', 'Umbrella')
artists = ('Adele', 'Rihanna')
songs = {'titles_artists': zip(titles, artist)}

in your template: 在您的模板中:

{% for title, artist in titles_artists %}
    <p>{{ title }}<br>{{ artist }}</p>
{% endfor %}

You can try rethink your context dictionary, something like: 您可以尝试重新考虑上下文字典,例如:

songs = {'artists': [
                        {'name': 'Adele', 'titles': ['Hello', ]}, 
                        {'name': 'Rihanna', 'titles': ['Umbrella', ]}
                    ]
        }

And in your template: 在您的模板中:

{% for artist in artists %}
    {% for title in artist.titles %}
         {{ title }}
    {% endfor %}
    {{ artist.name }}
{% endfor %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何遍历元组 (str),然后返回包含键(来自元组)和键索引作为值的字典? - How can you iterate through a tuple (str), then return a dictionary containing the keys (from the tuple) and the index of the keys as the values? 如何在 Django 模板中使用列表迭代字典作为值? - How do I iterate dictionary with lists as values in Django template? 如何更改字典中的元组值? - How do I change tuple values in a dictionary? 如何将包含三个元素的元组转换为包含一个键和两个值的字典? - How do you turn a tuple with three elements into a dictionary containing a key and two values? 如何计算元组列表并将变量的频率导出到字典中? - How do you count a tuple list and export the frequency of the variables into a dictionary? 如何使用 Pandas 映射嵌套在字典中的元组的索引? - How do you map the index of a tuple nested in a dictionary using Pandas? 如何在字典值中的元组中搜索数字? - How do I search for number in tuple which is in dictionary values? Django模板——迭代一个元组列表,每个元组都是一个字符串,字典 - Django template - iterate a list of tuples, each tuple is a string, dictionary 如何在Django模板中遍历字典? - How do I iterate through a dictionary in Django Templates? 如何在 Django 中将字典迭代到模板 - How to iterate dictionary to template in Django
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM