I have a list of dictionary
in python i.e.
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 of the keys and value of listofobs
variable in a Django-template. For example:
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
and so on ..
In Python, to iterate the dictionary ( dict ) with a for loop, use keys() , values() , items() methods. You can also get a list of all keys and values in the dictionary with those methods and list() . Use the following dictionary as an example. You can iterate keys by using the dictionary object directly in a for loop.
You can iterate through a Python dictionary using the keys(), items(), and values() methods. keys() returns an iterable list of dictionary keys. items() returns the key-value pairs in a dictionary.
You can loop through a dictionary by using a for loop. When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.
To iterate through the values of the dictionary elements, utilise the values() method that the dictionary provides. An iterable of all the values for each item that is available in the dictionary is returned. You can then go through the numbers as shown below by using a for loop.
Django template syntax lets you loop over a list of dicts:
{% for obj in listofobjs %}
timestamp = {{ obj.timestamp }}
ip = {{ obj.ip }}
user = {{ obj.user }}
{% endfor %}
All you need to is make sure listofobjs is in your context for rendering.
for a in listofobs:
print str( a['timestamp'] ), a['ip'], a['user']
Will iterate over the list of dict's, then to use them in the template just wrap it in the needed django syntax and which is quite similar to regular python.
Look at the examples for the built in for
template tag.
Looping over items (your outer loop):
{% for obj in listofobjs %}
{# do something with obj (just print it for now) #}
{{ obj }}
{% endfor %}
And then loop over the items in your dictionary object:
{% for key, value in obj.items %}
{{ key }}: {{ value }}
{% endfor %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With