Django array or list output?


I'm pulling a set of image urls and their respective titles. I've tried creating a hash or associative array, but the data seems to overwrite so I only end up with the last item in the array.

For example;

thumbnail_list = []
for file in media:
    thumbnail_list['url'] = file.url
    thumbnail_list['title'] = file.title

I've even tried creating two lists and putting them in a larger one.

all_thumbs = [thumbnail_list], [thumbnail_urls]

I'm trying to create a link out of this data:

<a href="image-url">image title</a>

I keep getting close, but I end up looping over too much data or all of the data at once in my django template.


Edit: Maybe zip() is what I need?

questions = ['name', 'quest', 'favorite color']
answers = ['lancelot', 'the holy grail', 'blue']
for q, a in zip(questions, answers):
    print 'What is your {0}?  It is {1}.'.format(q, a)
2/24/2010 9:35:11 AM

Accepted Answer

You want a dict, which is Python's associative data structure, whereas you are creating a list.

But I'm not sure I understand your problem. Why not just pass your media collection into the template and iterate like this:

{% for file in media %}
    <a href="{{ file.url }}">{{ file.title }}</a>
{% endfor %}


Based on your comment, I now presume you are looking for something like this:

thumbnail_list = []
for file in media:
    file_info = {}
    file_info['url'] = file.url
    file_info['title'] = file.title

{% for file in thumbnail_list %}
    <a href="{{ file.url }}">{{ file.title }}</a>
{% endfor %}

You can create a list, then for each file, append a dictionary into that list after you've processed the URL, title, or whatever.

Or, you could create your own class that encapsulates this a little better in case you have other logic to apply:

class FileInfo(object):
    def __init__(self, file):
        self.url = file.url # do whatever
        self.title = file.title # do whatever

thumbnail_list = []
for file in media:
2/24/2010 12:17:44 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow