python – Getting a list of values from a list of dicts

python – Getting a list of values from a list of dicts

Assuming every dict has a value key, you can write (assuming your list is named l)

[d[value] for d in l]

If value might be missing, you can use

[d[value] for d in l if value in d]

Heres another way to do it using map() and lambda functions:

>>> map(lambda d: d[value], l)

where l is the list.
I see this way sexiest, but I would do it using the list comprehension.

Update:
In case that value might be missing as a key use:

>>> map(lambda d: d.get(value, default value), l)

Update: Im also not a big fan of lambdas, I prefer to name things… this is how I would do it with that in mind:

>>> import operator
>>> get_value = operator.itemgetter(value)
>>> map(get_value, l)

I would even go further and create a sole function that explicitly says what I want to achieve:

>>> import operator, functools
>>> get_value = operator.itemgetter(value)
>>> get_values = functools.partial(map, get_value)
>>> get_values(l)
... [<list of values>]

With Python 3, since map returns an iterator, use list to return a list, e.g. list(map(operator.itemgetter(value), l)).

python – Getting a list of values from a list of dicts

[x[value] for x in list_of_dicts]

Leave a Reply

Your email address will not be published. Required fields are marked *