views:

362

answers:

1

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.

thumbnail_list.append('foo')
thumbnail_urls.append('bar')
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.

Ideas?

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)
+1  A: 

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 %}

EDIT

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
    thumbnail_list.append(file_info)

{% 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:
    thumbnail_list.append(FileInfo(file))
Joe Holloway
Hi Joe - I need to do a string replace on the URL and also not output any images that don't have a title. So I can only do that on the python side, correct?
Shu
UGH! I should have seen this earlier. thank you so much! Does that class FileInfo have to return anything or can I call it as is? e.g.; return self;
Shu
The `__init__` method is the Python constructor it doesn't need to return anything as it's return value is implied to be the new object.`file_info = FileInfo(...)`
Joe Holloway