How to iterate over a list of dictionaries in python?

I have a list of dictionary in python ie

 listofobs = [{'timestamp': datetime.datetime(2012, 7, 6, 12, 39, 52), 'ip': u'1.4.128.0', 'user': u'lovestone'}, {'timestamp': datetime.datetime(2012, 7, 6, 12, 40, 32), 'ip': u'192.168.21.45', 'user': u'b'}] 

I want to use all the keys and the value of the listofobs variable in a Django template. For instance:

For the first iteration:

 timestamp = 7 july 2012, 12:39 Am ip = 1.4.128.0 user = lovestone 

and for the second iteration:

  timestamp = 7 july 2012, 12:40 Am ip = 192.168.21.45 user = b 

etc.

+4
source share
3 answers
 for a in listofobs: print str( a['timestamp'] ), a['ip'], a['user'] 

It will iterate over the dict list and then use them in the template, just wrap it in the desired django syntax and which is very similar to regular python.

+8
source

The Django template syntax allows you to iterate over a list of dicts:

 {% for obj in listofobjs %} timestamp = {{ obj.timestamp }} ip = {{ obj.ip }} user = {{ obj.user }} {% endfor %} 

All you need to do is make sure listofobjs is in your context for rendering.

+3
source

See examples of inline for tags .

The cycle of elements (external circuit):

 {% for obj in listofobjs %} {# do something with obj (just print it for now) #} {{ obj }} {% endfor %} 

And then iterate over the elements in your dictionary:

 {% for key, value in obj.items %} {{ key }}: {{ value }} {% endfor %} 
+2
source

All Articles