31

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?

dublintech
  • 16,815
  • 29
  • 84
  • 115
  • 1
    Depends on what you want to do with it. If all you want to do is print it, this is fine. If you wanted to make a new list with some function of age (say the max), you could use a listcomp or genexp. But if you want to do a lot of branching on entry['age'], stick with the for loop. [And you can skip the semicolons ..] – DSM Feb 05 '12 at 19:55

4 Answers4

39

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.

Brigand
  • 84,529
  • 20
  • 165
  • 173
30

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]
Jaykumar Patel
  • 26,836
  • 12
  • 74
  • 76
7

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
senderle
  • 145,869
  • 36
  • 209
  • 233
3

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}".)

ben w
  • 2,490
  • 14
  • 19