Nick Heiner
Nick Heiner

Reputation: 122600

Python: How to use a list comprehension here?

I have data of the following form:

foos = [{'bar': [{'baz': 1}, {'baz': 2}]}, {'bar': [{'baz': 3}, {'baz': 4}]}, {'bar': [{'baz': 5}, {'baz': 6}]}]

I want a list comprehension that will yield:

[1, 2, 3, 4, 5, 6]

I'm not quite sure how to go about doing this. This sorta works:

>>> [[bar['baz'] for bar in foo['bar']] for foo in foos]
[[1, 2], [3, 4], [5, 6]]

but I want the results to be a flattened list.

Upvotes: 4

Views: 220

Answers (3)

6502
6502

Reputation: 114579

this will do

 [y['baz'] for x in foos for y in x['bar']]

If you think it's not really natural I agree.

Probably explicit code would be better unless there are other reasons to do that.

Upvotes: 4

Rita
Rita

Reputation: 31

foos = [{'bar': [{'baz': 1}, {'baz': 2}]}, {'bar': [{'baz': 3}, {'baz': 4}]}, {'bar': [{'baz': 5}, {'baz': 6}]}]

for x in foos:
  for y in x:

    for i in range(len(x[y])):
      for z in x[y][i]:
        print x[y][i][z]

Upvotes: 0

unutbu
unutbu

Reputation: 880777

Instead of nesting list comprehensions, you can do it with two for .. in clauses in one list comprehension:

In [19]: [item['baz'] for foo in foos for item in foo['bar']]
Out[19]: [1, 2, 3, 4, 5, 6]

Note that

[... for foo in foos for item in foo['bar']]

translates roughly into

for foo in foos:
    for item in foo['bar']:
        ...

Upvotes: 10

Related Questions