Iterating over list of dictionaries

Question:

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?

Asked By: dublintech

||

Answers:

For printing, probably what you’re doing is just about right. But if you want to store the values, you could use a list comprehension:

>>> d_list = [dict((('age', x), ('foo', 1))) for x in range(10)]
>>> d_list
[{'age': 0, 'foo': 1}, {'age': 1, 'foo': 1}, {'age': 2, 'foo': 1}, {'age': 3, 'foo': 1}, {'age': 4, 'foo': 1}, {'age': 5, 'foo': 1}, {'age': 6, 'foo': 1}, {'age': 7, 'foo': 1}, {'age': 8, 'foo': 1}, {'age': 9, 'foo': 1}]
>>> ages = [d['age'] for d in d_list]
>>> ages
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> len(ages)
10
Answered By: senderle

The semicolons at the end of lines aren’t necessary in Python (though you can use them if you want to put multiple statements on the same line). So it would be more pythonic to omit them.

But the actual iteration strategy is easy to follow and pretty explicit about what you’re doing. There are other ways to do it. But an explicit for-loop is perfectly pythonic.

(Niklas B.’s answer will not do precisely what you’re doing: if you want to do something like that, the format string should be "{0}n{1}".)

Answered By: ben w

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.

Answered By: 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]
Answered By: Jaykumar Patel
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.