Reputation: 5049
With a list of dicts like below
a = [{'a': 1, 'b': [{'c': [1, 2, 3], 'd': 4}, {'c': [5, 6, 1], 'd': 7}]}, {'a': 2, 'b': [{'c': [2, 3, 4], 'd': 5}, {'c': [7, 6, 1], 'd': 8}]}]
need to extract values for the key b
into another list
I could do the following
b = []
for item in a:
b+= item['b']
this gives [{'c': [1, 2, 3], 'd': 4}, {'c': [5, 6, 1], 'd': 7}, {'c': [2, 3, 4], 'd': 5}, {'c': [7, 6, 1], 'd': 8}]
which is fine.
I'm trying to learn list comprehension and wanted to know how this could be done. I tried the following
[ item['b'] for item in a]
. However that give a list of lists like below.
[[{'c': [1, 2, 3], 'd': 4}, {'c': [5, 6, 1], 'd': 7}], [{'c': [2, 3, 4], 'd': 5}, {'c': [7, 6, 1], 'd': 8}]]
Upvotes: 1
Views: 62
Reputation: 73
You can try the following solutions. Solution at number (2) uses Python "itertools" module.
(1)
a = [{'a': 1, 'b': [{'c': [1, 2, 3], 'd': 4}, {'c': [5, 6, 1], 'd': 7}]}, {'a': 2, 'b': [{'c': [2, 3, 4], 'd': 5}, {'c': [7, 6, 1], 'd': 8}]}]
[ r for item in a for r in item['b']]
Output...
[{'c': [1, 2, 3], 'd': 4},
{'c': [5, 6, 1], 'd': 7},
{'c': [2, 3, 4], 'd': 5},
{'c': [7, 6, 1], 'd': 8}]
(2)
a = [{'a': 1, 'b': [{'c': [1, 2, 3], 'd': 4}, {'c': [5, 6, 1], 'd': 7}]}, {'a': 2, 'b': [{'c': [2, 3, 4], 'd': 5}, {'c': [7, 6, 1], 'd': 8}]}]
import itertools
list(itertools.chain.from_iterable([item['b'] for item in a]))
Output...
[{'c': [1, 2, 3], 'd': 4},
{'c': [5, 6, 1], 'd': 7},
{'c': [2, 3, 4], 'd': 5},
{'c': [7, 6, 1], 'd': 8}]
Upvotes: 1
Reputation: 2657
I would try something like this, just keep in mind the outer loop would come first than the inner loop in the list comprehension
a = [{'a': 1, 'b': [{'c': [1, 2, 3], 'd': 4}, {'c': [5, 6, 1], 'd': 7}]}, {'a': 2, 'b': [{'c': [2, 3, 4], 'd': 5}, {'c': [7, 6, 1], 'd': 8}]}]
b = [ c for d in a for c in d['b']]
print(b)
OUTPUTS:
[{'c': [1, 2, 3], 'd': 4}, {'c': [5, 6, 1], 'd': 7}, {'c': [2, 3, 4], 'd': 5}, {'c': [7, 6, 1], 'd': 8}]
Upvotes: 5