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]
Here's 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: I'm 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))
.
[x['value'] for x in list_of_dicts]
For a very simple case like this, a comprehension, as in Ismail Badawi's answer is definitely the way to go.
But when things get more complicated, and you need to start writing multi-clause or nested comprehensions with complex expressions in them, it's worth looking into other alternatives. There are a few different (quasi-)standard ways to specify XPath-style searches on nested dict-and-list structures, such as JSONPath, DPath, and KVC. And there are nice libraries on PyPI for them.
Here's an example with the library named dpath
, showing how it can simplify something just a bit more complicated:
>>> dd = {
... 'fruits': [{'value': 'apple', 'blah': 2}, {'value': 'banana', 'blah': 3}],
... 'vehicles': [{'value': 'cars', 'blah':4}]}
>>> {key: [{'value': d['value']} for d in value] for key, value in dd.items()}
{'fruits': [{'value': 'apple'}, {'value': 'banana'}],
'vehicles': [{'value': 'cars'}]}
>>> dpath.util.search(dd, '*/*/value')
{'fruits': [{'value': 'apple'}, {'value': 'banana'}],
'vehicles': [{'value': 'cars'}]}
Or, using jsonpath-ng
:
>>> [d['value'] for key, value in dd.items() for d in value]
['apple', 'banana', 'cars']
>>> [m.value for m in jsonpath_ng.parse('*.[*].value').find(dd)]
['apple', 'banana', 'cars']
This one may not look quite as simple at first glance, because find
returns match objects, which include all kinds of things besides just the matched value, such as a path directly to each item. But for more complex expressions, being able to specify a path like '*.[*].value'
instead of a comprehension clause for each *
can make a big difference. Plus, JSONPath is a language-agnostic specification, and there are even online testers that can be very handy for debugging.