Iterating over a dictionary

2 views
Skip to first unread message

Todd O'Bryan

unread,
Apr 24, 2006, 8:30:38 PM4/24/06
to django...@googlegroups.com
I'm trying to display the values from a form on a summary page using
a template. (Actually, I'm trying to do something more complicated,
but let's start here.) Using {% debug %} I can see that, for example,

answers = { 'a':1, 'b':2, 'c':3 }

and in my template I have

{% for answer in answers.keys %}
{{answer}} = {{answers.answer}}<br/>
{% endfor %}

I would expect this to print

a = 1
b = 2
c = 3

but I get

a =
b =
c =

Am I wrong that the dot notation is supposed to do dictionary lookup
or is there some other way to do this?

(I'm using m-r 2746.)

Thanks,
Todd

Malcolm Tredinnick

unread,
Apr 24, 2006, 8:40:57 PM4/24/06
to django...@googlegroups.com
Hi Todd,

The problem you are encountering is that Django is looking for the
literal key 'answer' in your dictionary. It does not do indirection in
the way you are expecting (look at the value of 'answer' and then use
that value to do the lookup.

To achieve what you are after, you can do this:

{% for answer in answers.items %}
{{ answer.0 }} = {{ answer.1 }}<br/>
{% endfor %}

This will give you the answer in arbitrary order, however. If you want
to sort things, you can use a slightly undocumented side-effect of the
dictsort filter and apply it to the list in the loop head (the
undocumented fact is that "|dictsort" works on lists like this, not just
dictionaries):

{% for answer in answers.items|dictsort:"0" %}
{{ answer.0 }} = {{ answer.1 }}<br/>
{% endfor %}

This will sort on the "key" in the dictionary -- the first argument in
each tuple in the list.

Cheers,
Malcolm

Ned Batchelder

unread,
Apr 24, 2006, 8:46:13 PM4/24/06
to django...@googlegroups.com
The dot notation {{answers.answer}} is equivalent to these Python
expressions:

answers['answer']
answers.answer
answers.answer()

you want:

answers[answer]

but the template engine doesn't know that you mean answer to be a
variable rather than a literal.

--Ned.

--
Ned Batchelder, http://nedbatchelder.com

Reply all
Reply to author
Forward
0 new messages