How do I extract all the values of a specific key from a list of dictionaries?

If you just need to iterate over the values once, use the generator expression:

generator = ( item['value'] for item in test_data )

...

for i in generator:
    do_something(i)

Another (esoteric) option might be to use map with itemgetter – it could be slightly faster than the generator expression, or not, depending on circumstances:

from operator import itemgetter

generator = map(itemgetter('value'), test_data)

And if you absolutely need a list, a list comprehension is faster than iterated list.append, thus:

results = [ item['value'] for item in test_data ]

Leave a Comment