views:

459

answers:

2

I am trying to loop over a dictionary, specifically the request object's meta property. It is a dictionary, but the following code is treating it like it is a list of strings. How can I do this correctly?

EDIT: I found that if I replace request.META with request.META.items, this works, but why does the following not work? Is it not a dict?

{% for a, b in request.META %}
    {{ a }}: {{ b }}
{% endfor %}

Yields (this is shortened for brevity):

G: D
w: s
R: U
H: T
G: N
...
L: S
R: E
H: T
P: A

Whereas:

{{request.META}}

Yields:

{'GDM_KEYBOARD_LAYOUT': 'us',
'wsgi.multiprocess': False,
'RUN_MAIN': 'true',
'HTTP_COOKIE': 'sessionid=...
...
...6:*.spx=00;36:*.xspf=00;36:',
'REMOTE_HOST': '',
'HTTP_ACCEPT_ENCODING': 'gzip,deflate',
'PATH_INFO': u'/'}
A: 

Replacing request.META with request.META.items works.

kzh
+1  A: 

Well, that's fairly simple.

request.META is a dictionary, right? So if you do a for loop over a dict you get its keys. That is what you are getting. And since the keys are strings (in your example) and the strings can be unpacked, their first and second items (characters) get unpacked into a and b.

The items method of the dictionary, however, yields a list of 2-tuples, each of those tuples get unpacked into a and b, respectively. So, it "works", as you say it.

shylent
Right, because I can't do {% for (a, b) in request.META %} with the parenthesis. Thanks.
kzh