Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over list of dictionaries

Tags:

python

I have a list -myList - where each element is a dictionary. I wish to iterate over this list but I am only interesting in one attribute - 'age' - in each dictionary each time. I am also interested in keeping count of the number of iterations.

I do:

for i, entry in enumerate(myList):     print i;     print entry['age'];  

But was wondering is there something more pythonic. Any tips?

like image 287
dublintech Avatar asked Feb 05 '12 19:02

dublintech


People also ask

How do I iterate a list of dictionaries?

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?

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.

Is iterating through a dictionary faster than a list?

Using iteritems is a tad bit faster... But the time to create a view is negligable; it is actually slower to iterate over than a list. This means that in Python 3, if you want to iterate many times over the items in a dictionary, and performance is critical, you can get a 30% speedup by caching the view as a list.


2 Answers

You could use a generator to only grab ages.

# Get a dictionary  myList = [{'age':x} for x in range(1,10)]  # Enumerate ages for i, age in enumerate(d['age'] for d in myList):      print i,age 

And, yeah, don't use semicolons.

like image 59
Brigand Avatar answered Sep 18 '22 17:09

Brigand


Very simple way, list of dictionary iterate

>>> my_list [{'age': 0, 'name': 'A'}, {'age': 1, 'name': 'B'}, {'age': 2, 'name': 'C'}, {'age': 3, 'name': 'D'}, {'age': 4, 'name': 'E'}, {'age': 5, 'name': 'F'}]  >>> ages = [li['age'] for li in my_list]  >>> ages [0, 1, 2, 3, 4, 5] 
like image 39
Jaykumar Patel Avatar answered Sep 19 '22 17:09

Jaykumar Patel