Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over list of dictionary in python?

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 ..

like image 392
Amit Pal Avatar asked Jul 06 '12 23:07

Amit Pal


People also ask

How do I iterate a list of dictionaries in Python?

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.

Can you iterate over a dictionary Python?

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.

Can you iterate over 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.

How do I iterate through a dictionary item?

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.


3 Answers

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.

like image 40
Ned Batchelder Avatar answered Nov 03 '22 01:11

Ned Batchelder


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.

like image 169
sean Avatar answered Nov 03 '22 01:11

sean


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 %}
like image 37
istruble Avatar answered Nov 03 '22 00:11

istruble