It seems I’ve never looped through a dict in Python before. I just assumed that it would work the same as with a PHP associative array, since the syntax of creating one is fairly similar. I just thought this would work:
for key, value in somedict: print key, ': ', value
But I guess not.
You have to call the items
or iteritems
functions on the dictionary, where iteritems
is faster, but also doesn’t allow certain actions that items
might:
for key, value in somedict.iteritems(): print key, ': ', value
I was trying to loop through a dictionary in a django template like so:
{% for key, value in somedict %}
{{ key }}: {{ value }}<br/>
{% endfor %}
Which, since it just skips over most errors, generated this response:
: : : : :
Which I only later found out was caused by an error when trying it in some regular python code. It should be:
{% for key, value in somedict.iteritems %}
{{ key }}: {{ value }}<br/>
{% endfor %}
I feel like this shouldn’t have happened to me. Oh well, now I know…
Advertisements