"for key, value" in 0.96

0 views
Skip to first unread message

Jose Jiménez

unread,
Feb 25, 2008, 1:21:05 PM2/25/08
to Django users
Hello everybody,

i'm developing an application with the lates stable release of django
(0.96).
In the trunk version, i can do "for key, value in variable", but in
the 0.96 version i take an error:

'for' statements with five words should end in 'reversed': for key,
value in variable

How can i access to the key and the value of all elements of a
dictionary? If i do: for a in variable, a is the key, but i can't
access its value.

Thanks.

Tom Badran

unread,
Feb 25, 2008, 3:48:08 PM2/25/08
to django...@googlegroups.com
Do "for k,v in dict.iteritems()"

Tom
--
Tom Badran
http://badrunner.net

Russell Keith-Magee

unread,
Feb 25, 2008, 5:54:11 PM2/25/08
to django...@googlegroups.com
On Tue, Feb 26, 2008 at 3:21 AM, Jose Jiménez <jjimen...@gmail.com> wrote:
>
> How can i access to the key and the value of all elements of a
> dictionary? If i do: for a in variable, a is the key, but i can't
> access its value.

The {% for key,value in list %} syntax was added in the trunk. In
0.96, you can't roll out tuples in a for loop; you are restricted to
saying {% for value in list %}. However, if "list" is a list of
tuples, you can use {{ value.0 }}, {{ value.1 }} to reference elements
in the tuple.

By default, iterating over a dictionary {% for key in dict %} provides
a list of keys. However dict.items() will provide a list of (key,
value) tuples (Tom's suggestion will also work - it provides an
iterator over tuples). If you then use {% for entry in dict.items %},
{{ entry }} will be a tuple, {{ entry.0 }} will be the key, and {{
entry.1 }} will be the value for the key.

Yours,
Russ Magee %-)

Malcolm Tredinnick

unread,
Feb 25, 2008, 6:02:11 PM2/25/08
to django...@googlegroups.com

So you are talking about the "for" template tag here, not Python code
(best to be clear about that). It also sounds like your "variable" is a
dictionary from your use of the words "key" and "value". Working on
those assumptions:

{% for value in variable.items %}
{{ value.0 }} is the key
{{ value.1 }} is the value
{% endfor %}

Here, variable.items returns a tuple and you can access the items in a
tuple via value.0 and value.1.

Malcolm

--
Why can't you be a non-conformist like everyone else?
http://www.pointy-stick.com/blog/

Jose Jiménez

unread,
Mar 4, 2008, 12:59:06 PM3/4/08
to Django users
Thank you very much everybody. I suspect that was a trunk's
functionality.

I solved it using a list of tuples.

Thanks again.
Reply all
Reply to author
Forward
0 new messages